JSFiddle - React, Tailwind, and code Playground
JavaScript
var contextClass = (window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.oAudioContext || window.msAudioContext);
if (contextClass) {
// Web Audio API is available.
var context = new contextClass();
} else {
// Web Audio API is not available. Ask the user to use a supported browser.
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
navigator.getUserMedia({
audio: true
}, gotStream);
function gotStream(stream) {
var mediaStreamSource = context.createMediaStreamSource(stream);
var gainNode = context.createGain();
gainNode.gain.value = 3;
var levelChecker = context.createScriptProcessor(2048);
mediaStreamSource.connect(gainNode);
gainNode.connect(levelChecker);
//Commenting out the line directly below stops the script processor from working!
levelChecker.connect(context.destination);
levelChecker.onaudioprocess = process;
}
function process(e) {
var buffer = e.inputBuffer.getChannelData(0);
var maxVal = 0;
// Iterate through buffer to check if any of the values exceeds 1.
for (var i = 0; i < buffer.length; i++) {
if (maxVal < buffer[i]) {
maxVal = buffer[i];
}
}
console.log(Math.round(maxVal * 100) + "%");
}