-
Notifications
You must be signed in to change notification settings - Fork 28
/
microphone-worklet.js
56 lines (47 loc) · 1.22 KB
/
microphone-worklet.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
const numTicks = 1;
let tick = 0;
let sampleSum = 0;
let numSamples = 0;
let muted = true;
class VolumeProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.port.addEventListener('message', e => {
const data = JSON.parse(e.data);
const {method} = data;
if (method === 'muted') {
muted = data.muted;
}
});
this.port.start();
}
process(inputs, outputs) {
const channels = inputs[0];
// const output = outputs[0];
// for (let i = 0; i < channels.length; i++) {
const i = 0;
const samples = channels[i];
for (let j = 0; j < samples.length; j++) {
sampleSum += Math.abs(samples[j]);
}
numSamples += samples.length;
// }
if (++tick >= numTicks) {
this.port.postMessage(sampleSum / numSamples);
tick = 0;
sampleSum = 0;
numSamples = 0;
}
if (!muted) {
for (let i = 0; i < outputs.length; i++) {
const input = inputs[i];
const output = outputs[i];
for (let channel = 0; channel < output.length; channel++) {
output[channel].set(input[channel]);
}
}
}
return true;
}
}
registerProcessor('volume-processor', VolumeProcessor);