-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (98 loc) · 2.46 KB
/
index.js
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
// Offscreen document
globalThis.bc = new BroadcastChannel("offscreen");
bc.addEventListener("message", async (e) => {
if (e.data === "resume") {
await workletStream.ac.resume();
}
if (e.data === "suspend") {
await workletStream.ac.suspend();
}
});
class AudioWorkletStream {
constructor({
codecs = ["audio/wav"],
urls = [""],
sampleRate = 44100,
numberOfChannels = 2,
latencyHint = 0.33,
workletOptions = {},
} = {}) {
Object.assign(this, {
ac: new AudioContext({
sampleRate,
numberOfChannels,
latencyHint,
}),
codecs,
urls,
sampleRate,
numberOfChannels,
latencyHint,
workletOptions,
});
}
async start() {
console.log(this.ac.baseLatency);
this.ac.addEventListener("statechange", this.handleEvents);
await this.ac.audioWorklet.addModule("audioWorklet.js");
this.aw = new AudioWorkletNode(
this.ac,
"audio-worklet-stream",
this.workletOptions,
);
this.aw.connect(this.ac.destination);
this.worker = new Worker("worker.js", {
type: "module",
});
this.worker.postMessage({
urls: this.urls,
}, [this.aw.port]);
this.worker.addEventListener("message", async (e) => {
if (e.data.ended) {
console.log(
"AudioWorklet stream done.",
e.data.currentTime,
e.data.currentFrame,
);
await this.stop();
}
});
}
async stop() {
await this.ac.suspend();
this.aw.disconnect();
this.aw.port.close();
await this.ac.close();
this.worker.terminate();
globalThis.close();
}
handleEvents(e) {
globalThis.console.log(
e.type === "statechange"
? "AudioContext.state:" + e.target.state
: e.type,
);
}
}
let origin = "https://github.com/guest271314/AudioWorkletStream/raw/master/";
// Define this globally so we can inspect and manipulate in DevTools
globalThis.workletStream = new AudioWorkletStream({
urls: Array.from({
length: 4,
}, (_, index) => `${origin}house--64kbs-${index}-wav`),
// urls: ["https://ia800301.us.archive.org/10/items/DELTAnine2013-12-11.WAV/Deltanine121113Pt3Wav.wav"],
latencyHint: 0,
workletOptions: {
numberOfInputs: 1,
numberOfOutputs: 2,
outputChannelCount: [2, 2],
processorOptions: {
codec: "audio/wav",
offset: 0,
index: 0,
key: 0,
bytes: 0,
},
},
});
globalThis.workletStream.start().catch(console.error);