-
Notifications
You must be signed in to change notification settings - Fork 3
/
volume-processor.js
55 lines (44 loc) · 1.64 KB
/
volume-processor.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
const SMOOTHING_FACTOR = 0.8;
const MINIMUM_VALUE = 0.00001;
// This is the way to register an AudioWorkletProcessor
// it's necessary to declare a name, in this case
// the name is "vumeter"
registerProcessor('volume', class extends AudioWorkletProcessor {
//_volume
_updateIntervalInMS
_nextUpdateFrame
constructor () {
super();
//this._volume = 0;
this._updateIntervalInMS = 40; // analyse 25 times per second (.onaudioprocess occurs between 23 and 24 times a seocnd)
this._nextUpdateFrame = this._updateIntervalInMS;
/*this.port.onmessage = event => {
if (event.data.updateIntervalInMS)
this._updateIntervalInMS = event.data.updateIntervalInMS;
}*/
}
get intervalInFrames () {
return this._updateIntervalInMS / 1000 * sampleRate;
}
process (inputs, outputs, parameters) {
const input = inputs[0];
// Note that the input will be down-mixed to mono; however, if no inputs are
// connected then zero channels will be passed in.
if (input.length > 0) {
const samples = input[0];
let sum = 0, i = 0;
let rms = 0;
// Calculated the squared-sum.
while (i < samples.length) sum += Math.abs(samples[i++]);
// Calculate the RMS level and update the volume.
rms = Math.sqrt(sum / samples.length);
// Update and sync the volume property with the main thread.
this._nextUpdateFrame -= samples.length;
if (this._nextUpdateFrame < 0) {
this._nextUpdateFrame += this.intervalInFrames;
this.port.postMessage({rms: rms}); // If we remove the if-condition, this happens 380x per second
}
}
return true;
}
});