-
Notifications
You must be signed in to change notification settings - Fork 0
/
volume-meter.js
59 lines (57 loc) · 1.95 KB
/
volume-meter.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
function createAudioMeter(audioContext, clipLevel, averaging, clipLag) {
var processor = audioContext.createScriptProcessor(512);
processor.onaudioprocess = volumeAudioProcess;
processor.clipping = false;
processor.lastClip = 0;
processor.volume = 0;
processor.clipLevel = clipLevel || 0.98;
processor.averaging = averaging || 0.95;
processor.clipLag = clipLag || 750;
// this will have no effect, since we don't copy the input to the output,
// but works around a current Chrome bug.
processor.connect(audioContext.destination);
processor.checkClipping = function () {
if (!this.clipping) return false;
if (this.lastClip + this.clipLag < window.performance.now())
this.clipping = false;
return this.clipping;
};
processor.shutdown = function () {
this.disconnect();
this.onaudioprocess = null;
};
return processor;
}
let debounce = false;
function volumeAudioProcess(event) {
document.querySelector(".step#enable-microphone").style.display = "none";
document.querySelector(".step#volume-bar").style.display = "block";
var buf = event.inputBuffer.getChannelData(0);
var bufLength = buf.length;
var sum = 0;
var x;
// Do a root-mean-square on the samples: sum up the squares...
for (var i = 0; i < bufLength; i++) {
x = buf[i];
if (Math.abs(x) >= this.clipLevel) {
this.clipping = true;
this.lastClip = window.performance.now();
}
sum += x * x;
}
// ... then take the square root of the sum.
var rms = Math.sqrt(sum / bufLength);
// Now smooth this out with the averaging factor applied
// to the previous sample - take the max here because we
// want "fast attack, slow release."
this.volume = Math.max(rms, this.volume * this.averaging);
document.querySelector("#level-bar").style.width = this.volume * 100 + "%";
if (debounce) {
return;
}
if (this.volume > thumb.value / 100) {
debounce = true;
setTimeout(() => (debounce = false), 250);
stopVideo();
}
}