Web Audio Spectrum Analyser

The Web Audio API is a treasure trove of great stuff you can do with an Audio Element. My objective was to create simple audio visualization of an audio stream from a provided audio file.

Key principles

We add the audio element into the root html file. We need access to it in our javascript.
<audio id="player" class="audio-player" src="media/weak_spot.mp3" controls="controls"></audio>

We are required to setup a few objects including a new AudioContext(), the Audio Element, document.getElementById('player') and the analyser using our context.createAnalyser() method.

We define our fftSize of our analyser, analyser.fftSize = 64. A great article goes into further detail about it, but to summarise:

The FFT size defines the number of bins used for dividing the window into equal strips, or bins. Hence, a bin is a spectrum sample, and defines the frequency resolution of the window.

We are now ready to start listening to the audio. We use the canplay event which is called when enough of the audio data has been loaded. First we create MediaElementAudioSourceNode object from our Audio Element. We can now connect our Analyser Object to the Source Node. We also need to connect our audio context destination to the analyser, basically a link to the final destination of all audio in the context.

audioElement.addEventListener("canplay", function() {  
  let source = context.createMediaElementSource(audioElement);
  source.connect(analyser);
  analyser.connect(context.destination);
});

The values we get from our analyser are Uint8, whole values between 0 and 255, so we setup an array of a determined length. The frequencyBinCount basically is the fftSize / 2. We had that value at 64, so our frequency data should return 32 bins within each sample window.

let frequencyData = new Uint8Array(analyser.frequencyBinCount);  
analyser.getByteFrequencyData(frequencyData);  

We can now run our update loop to read the values from the Audio Context. The values are actually read from the current stream of data. If you pause your audio, your bytes frequency data will also be zero.

Just remember that in the update loop you also need to call analyser.getByteFrequencyData(frequencyData) to get the latest frequency data at each new frame.

Check out the live demo or fork the code and play around with the properties. Let me know if you have some great examples of web based visualizers in the comments below!

Audio Spectrum Demo