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
Please Login or Register to comment.
13 Comments.
  • avatar
    Guest  
    12/06/2020
    I have to get across my love for your generosity in support of those individuals that have the need for guidance on the field. Your very own commitment to getting the message all around appears to be really powerful and has continuously permitted people much like me to reach their pursuits. This interesting publication entails so much a person like me and additionally to my mates. Regards; from everyone of us.
    lebron 16 http://www.lebron16.us
  • avatar
    Guest  
    09/06/2020
    I am commenting to let you understand what a cool discovery my cousin's girl found using your web site. She picked up a good number of details, with the inclusion of what it's like to possess an incredible coaching nature to let a number of people without difficulty learn various advanced topics. You actually exceeded our expected results. Thank you for giving those productive, trusted, edifying and also cool guidance on that topic to Tanya.
    nike air max 97 http://www.nikeairmax97.net
  • avatar
    Guest  
    06/06/2020
    I am just commenting to make you know of the wonderful discovery my child had reading through your webblog. She learned plenty of details, which included what it's like to possess an ideal coaching mood to make the others smoothly learn about a variety of specialized issues. You truly did more than people's expected results. I appreciate you for showing those powerful, trusted, explanatory not to mention unique guidance on that topic to Lizeth.
    golden goose outlet http://www.goldengoose.us.com
  • avatar
    Guest  
    05/06/2020
    I happen to be writing to make you know what a amazing discovery my cousin's child enjoyed going through your webblog. She realized numerous issues, most notably what it is like to have a marvelous helping spirit to let other people completely know precisely specified very confusing matters. You truly did more than our own desires. Thank you for producing these powerful, safe, edifying and also easy guidance on this topic to Tanya.
    <a href="http://www.kyrie6shoes.us" >nike kyrie 6</a>
  • avatar
    Guest  
    05/06/2020
    I must voice my affection for your generosity supporting men and women who have the need for help with this particular niche. Your real commitment to passing the solution up and down turned out to be exceptionally useful and have specifically empowered regular people much like me to reach their pursuits. The warm and friendly report can mean a whole lot a person like me and especially to my office colleagues. Warm regards; from all of us.
    bape hoodie http://www.bapehoodie.us
  • avatar
    Guest  
    03/06/2020
    I wish to convey my respect for your kindness giving support to men and women that must have help on in this concern. Your very own dedication to passing the solution throughout had been unbelievably effective and has usually made folks much like me to reach their dreams. Your personal informative guidelines implies a great deal to me and substantially more to my colleagues. Regards; from each one of us.
    louboutin outlet http://www.louboutin-outlet.us.com
  • avatar
    Guest  
    03/06/2020
    Thank you for all of the labor on this blog. My niece takes pleasure in managing internet research and it's really simple to grasp why. Almost all notice all relating to the dynamic mode you render very useful steps through the blog and in addition increase contribution from website visitors about this area plus our girl is undoubtedly discovering a lot. Enjoy the remaining portion of the year. You have been performing a pretty cool job.
    jordan 12 http://www.jordan12.us.com
  • avatar
    Guest  
    01/06/2020
    A lot of thanks for every one of your effort on this web page. My daughter enjoys managing research and it's really easy to understand why. Many of us learn all of the compelling manner you render powerful ideas through the web blog and inspire participation from other people on that matter plus our simple princess is in fact studying a lot. Have fun with the rest of the new year. You're doing a brilliant job.
    curry 6 shoes http://www.curry6shoes.us
  • avatar
    Guest  
    07/03/2019
    <!DOCTYPE HTML>
    <html>
    <head>
    <marquee>yeet<marquee/>
    • avatar
      Guest  
      01/06/2020
      I wish to express my appreciation for your kindness in support of folks who must have guidance on this matter. Your personal commitment to getting the solution around appeared to be quite useful and have permitted many people just like me to realize their aims. Your own important publication entails much to me and further more to my office colleagues. Many thanks; from all of us.
      <a href="http://www.monclers.us.org" >moncler jackets</a>
  • avatar
    Guest  
    22/03/2017
    Nice demo Bacon
    • avatar
      Guest  
      04/06/2020
      Thank you for all your valuable labor on this blog. My aunt delights in carrying out internet research and it's really simple to grasp why. Many of us learn all of the compelling form you make very helpful tricks by means of the web blog and in addition invigorate response from the others on this idea plus our simple princess is becoming educated a great deal. Enjoy the remaining portion of the new year. You are performing a useful job.
      <a href="http://www.goyardus.com" >goyard</a>
    • avatar
      Guest  
      06/06/2020
      Thank you for all of the effort on this website. My mom loves setting aside time for investigation and it is easy to see why. Most people notice all of the powerful medium you make efficient guidelines by means of the website and even improve response from other ones on the issue while our princess has been being taught so much. Take pleasure in the remaining portion of the new year. You are always carrying out a terrific job.
      <a href="http://www.ferragamobelt.us.org" >ferragamo belt</a>