-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.html
104 lines (102 loc) · 3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<!DOCTYPE html>
<html>
<head>
<title>Stream audio from Worker to AudioWorklet</title>
</head>
<body>
<button>Start Audio Playback</button>
<script>
if (globalThis.gc) {
gc();
}
// AudioWorkletStream
// Stream audio from Worker to AudioWorklet
// guest271314 2-24-2020
'use strict';
const handleEvents = e =>
globalThis.console.log(
e.type === 'statechange'
? 'AudioContext.state:' + e.target.state
: e.type
);
const button = document.querySelector('button');
class AudioWorkletStream {
constructor({
codecs = ['audio/wav'],
urls = [''],
sampleRate = 44100,
numberOfChannels = 2,
latencyHint = 0,
workletOptions = {},
} = {}) {
this.mediaStreamTrack = new Promise(async resolve => {
const ac = new AudioContext({
sampleRate,
numberOfChannels,
latencyHint,
});
await ac.suspend();
console.log(ac.baseLatency);
ac.onstatechange = handleEvents;
await ac.audioWorklet.addModule('audioWorklet.js');
// optionally pass MediaStreamTrack to resolve()
resolve();
const aw = new AudioWorkletNode(
ac,
'audio-data-worklet-stream',
workletOptions
);
aw.connect(ac.destination);
const worker = new Worker('worker.js', {
type: 'module',
});
worker.postMessage(
{
urls,
},
[aw.port]
);
worker.onmessage = async e => {
if (e.data.start) {
await ac.resume();
}
if (e.data.ended) {
console.log('audio worklet stream done', e.data.currentTime, e.data.currentFrame);
button.disabled = false;
button.textContent = 'Start Audio Playback';
await ac.suspend();
aw.disconnect();
aw.port.close();
await ac.close();
worker.terminate();
}
};
});
}
}
button.onclick = async _ => {
button.disabled = true;
button.textContent = 'Audio Playing';
// set parameters as arrays for potential "infinite" input, output stream
let workletStream = new AudioWorkletStream({
urls: [
'house--64kbs-0-wav',
'house--64kbs-1-wav',
'house--64kbs-2-wav',
'house--64kbs-3-wav',
],
latencyHint: 0,
workletOptions: {
numberOfInputs: 1,
numberOfOutputs: 2,
outputChannelCount: [2, 2],
processorOptions: {
codec: 'audio/wav',
offset: 0
},
},
});
};
</script>
</body>
</html>