concept-collection / voicenote
voicenote / worklet.js
30 lines · 872 BBlameHistoryRaw
1// AudioWorklet processor: batches mono input samples into ~512-sample chunks
2// and posts them to the main thread. Outputs silence (it is connected to the
3// destination only so the graph keeps pulling audio through it).
4class CaptureProcessor extends AudioWorkletProcessor {
5 constructor() {
6 super();
7 this.buf = new Float32Array(512);
8 this.n = 0;
9 }
11 process(inputs) {
12 const ch = inputs[0] && inputs[0][0];
13 if (ch) {
14 let i = 0;
15 while (i < ch.length) {
16 const take = Math.min(ch.length - i, this.buf.length - this.n);
17 this.buf.set(ch.subarray(i, i + take), this.n);
18 this.n += take;
19 i += take;
20 if (this.n === this.buf.length) {
21 this.port.postMessage(this.buf.slice());
22 this.n = 0;
23 }
24 }
25 }
26 return true;
27 }
30registerProcessor('capture', CaptureProcessor);