JSFiddle - React, Tailwind, and code Playground
by Daedalus
HTML
<audio id='v' controls crossOrigin="anonymous" src="https://upload.wikimedia.org/wikipedia/en/3/3d/Sample_of_Daft_Punk%27s_Da_Funk.ogg" type="video/mp4"></audio><br />
<div id="l" class="meter">
</div>
<div id="r" class="meter">
</div>
CSS
#l {
height: 20px;
display: block;
background-color: green;
}
#r {
height: 20px;
display: block;
background-color: red;
}
JavaScript
// HTML Elements
const audioElement = document.getElementById("v");
const peakMeterLeft = document.getElementById("l");
const peakMeterRight = document.getElementById("r");
// Audio Context
const audioContext = new AudioContext();
const source = audioContext.createMediaElementSource(audioElement);
const analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
source.connect(analyser);
analyser.connect(audioContext.destination);
// Peak Meters
function updatePeakMeters() {
analyser.getByteTimeDomainData(dataArray);
let sumLeft = 0;
let sumRight = 0;
for (let i = 0; i < bufferLength; i += 2) {
sumLeft += Math.abs(dataArray[i] - 128);
sumRight += Math.abs(dataArray[i + 1] - 128);
}
const peakValueLeft = sumLeft / (bufferLength / 2);
const peakValueRight = sumRight / (bufferLength / 2);
peakMeterLeft.style.width = peakValueLeft + "px";
peakMeterRight.style.width = peakValueRight + "px";
requestAnimationFrame(updatePeakMeters);
}
updatePeakMeters();