-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeter-processor.worklet.ts
44 lines (34 loc) · 1.33 KB
/
meter-processor.worklet.ts
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
import StoppableAudioWorkletProcessor from "./StoppableAudioWorkletProcessor";
const MESSAGE_CHANNELS = "channels";
const MESSAGE_LEVEL = "level";
class MeterProcessor extends StoppableAudioWorkletProcessor {
process(inputs: Float32Array[][]) {
const input = inputs[0];
if (input.length === 0) {
this.port.postMessage({ payload: { channel: 0, level: 0 }, type: MESSAGE_LEVEL });
this.port.postMessage({ payload: { channels: input.length }, type: MESSAGE_CHANNELS });
return this.running;
}
for (let channel = 0; channel < input.length; ++channel) {
const level = getMaxAmplitude(input[channel]);
this.port.postMessage({ payload: { channel, level }, type: MESSAGE_LEVEL });
}
this.port.postMessage({ payload: { channels: input.length }, type: MESSAGE_CHANNELS });
return this.running;
}
}
function getMaxAmplitude(buffer: Float32Array): number {
let maxAmplitude = 0;
const sampleFrames = buffer.length;
for (let i = 0; i < sampleFrames; i++) {
const amplitude = Math.abs(buffer[i]);
if (amplitude > maxAmplitude) {
maxAmplitude = amplitude;
}
}
return maxAmplitude;
}
registerProcessor("meter-processor", MeterProcessor);
// Fixes TypeScript error TS1208:
// File cannot be compiled under '--isolatedModules' because it is considered a global script file.
export {};