Visualizing audio Using canvas

We can create a visualization of your HTML5 audio using canvas.

snippet
<audio src="audio.ogg"></audio>
<canvas width="512" height="100"></canvas>
<button title="Generate Waveform" onclick="genWave();">Generate Waveform</button>
<script>
function genWave() {
var audio = document.getElementsByTagName("audio")[0];
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext('2d');
audio.addEventListener("MozAudioAvailable", buildWave, false);

function buildWave(event) {
var channels = audio.mozChannels;
var frameBufferLength = audio.mozFrameBufferLength;
var fbData = event.frameBuffer;
var stepInc = (frameBufferLength / channels) / canvas.width;
var waveAmp = canvas.height / 2;
canvas.width = canvas.width;
context.beginPath();
context.moveTo(0, waveAmp - fbData[0] * waveAmp);
for (var i = 1; i < canvas.width; i++) {
context.lineTo(i, waveAmp - fbData[i * stepInc] * waveAmp);
}
context.strokeStyle = "#fff";
context.stroke();
}
audio.play();
}
</script>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 # # # # #