The HTML5 Audio API allows this kind of visualization, with enough flexibility . Here's an adapted example of a MDN tutorial , picking up the audio of an element <audio>
and drawing the view in a <canvas>
:
WARNING: The example below no longer works inline because it uses an audio file from another domain, causing a warning of % of outputs zeroes due to CORS access restrictions in Chrome (and probably something similar in other browsers). If you test in your development environment or server, with local files, it works. Strangely, in the editing preview here the site also works.
var canvas = document.querySelector('canvas');
var audio = document.querySelector('audio');
var audioCtx = new AudioContext();
var source = audioCtx.createMediaElementSource(audio);
var analyser = audioCtx.createAnalyser();
source.connect(analyser);
source.connect(audioCtx.destination);
// CORS
audio.crossOrigin = "anonymous";
analyser.fftSize = 1024;
var bufferLength = analyser.fftSize;
var dataArray = new Uint8Array(bufferLength);
var w = canvas.width;
var h = canvas.height;
var sliceWidth = w * 1.0 / bufferLength;
canvasCtx = canvas.getContext('2d');
canvasCtx.clearRect(0, 0, w, h);
canvasCtx.fillStyle = 'rgb(200, 200, 200)';
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
function draw() {
drawVisual = requestAnimationFrame(draw);
analyser.getByteTimeDomainData(dataArray);
canvasCtx.fillRect(0, 0, w, h);
canvasCtx.beginPath();
var x = 0;
for(var i = 0; i < bufferLength; i++) {
var v = dataArray[i] / 128.0;
var y = v * h/2;
if(i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height/2);
canvasCtx.stroke();
};
draw();
<audio controls>
Your browser does not support the <code>audio</code> element.
<source src="//upload.wikimedia.org/wikipedia/commons/4/43/Goldberg_variations_1_start.ogg" type="audio/ogg" />
</audio>
<canvas width="600" height="150"></canvas>
Audio Credit: Wikimedia Commons , the opening excerpt from Variation 1 of the Goldberg Variations of Bach, BWV 988