Recently I have been doing some fiddling around with the Web Audio API for the audio player on img.baconics.com and I have to say, one can do some pretty cool things with it; one of those things being audio visualization with a little help from the Canvas API.

The HTML

The HTML is pretty straighforward, all we really need is the <audio> and <canvas> elements.
<!DOCTYPE HTML>
<html>
    <head>
        <script type="application/javascript">
            <!--
                THE JAVASCRIPT WILL GO HERE
            //-->
        </script>
    </head>
    <body>
        <audio id="media" controls >
             <source  src="audio.mp3" type="audio/mpeg" />
             Your browser does not support HTML audio.
        </audio>
        <canvas id="visualizer" width="400" height="200" />
    </body>
</html>

The JavaScript

First we need to create the audio context, connect an analyser node and get our source media. For the sake of simplicity we will just be using an <audio> element as our audio source with AudioContext.createMediaElementSource, however you do have other options for this which are outlined here.
//handle different audio context browser prefixes
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;

//create the audio context
var audioCtx = new (window.AudioContext)();

//create an audio analyser
var analyser = audioCtx.createAnalyser();

//get the audio source
var audio = document.getElementById('media');
var source = audioCtx.createMediaElementSource(audio);

//connect the audio context and the analyser
source.connect(analyser);

//actually output the audio to the speakers
analyser.connect(audioCtx.destination);

After setting up the audio context we need to set up the canvas context and the visualizer variables.
//handle different animation frame browser prefixes
window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame;
window.cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame;

//create the canvas context and set the animationId variable
var canvas = document.getElementById("visualizer");
var canvasCtx = canvas.getContext('2d');
var animationId = null;
    
//set the bar variables
var barWidth = 10; //the width of each bar
var barGap = 1; //the gap between each bar

The last thing we need to do is bring it all together so bars are actually drawn on the canvas. Since we do not need all of the audio data in our graph we will add a "step" value based off the length of the current buffer and the number of bars we want.
//the visualization function
var visualize = function() {
    //get the audio frequency information
    var bufferLength = analyser.frequencyBinCount;
    var array = new Uint8Array(bufferLength);
    
    analyser.getByteFrequencyData(array);
    
    //clear the canvas
    canvasCtx.clearRect(0, 0, canvas.width, canvas.height);
    
    //get a bar count and a step
    var barCount = Math.floor(canvas.width/(barWidth+barGap));
    var step = Math.ceil(bufferLength / barCount);
    
    //loop through the audio info
    for(var i = 0; i < barCount; i++) {
        var value = array[i*step];

        //draw the bar, the x position being the current bar number multiplied by the width+gap
        canvasCtx.fillStyle = '#000';
        canvasCtx.fillRect(i * (barWidth+barGap), canvas.height-value/2, barWidth, value);
    }
    
    animationId = window.requestAnimationFrame(visualize);
}

//begin the visualization
animationId = window.requestAnimationFrame(visualize);

Final Thoughts and Demo

Obviously this post is not an extensive look at using the Web Audio API to visualize audio and is by no means an example of best practices with the Web Audio API, it is however intended to be a brief introduction to the power of the Web Audio API.

Here is this visualizer in action:

DEMO

If you have any input or criticism, feel free to comment below.
Last edited 10:32 PM (UTC) on 19/05/2016 by Bacon.
avatar
Posted by: Bacon
16/04/2016
[spoil] [hr]
[Close Tags]
1 Comments.