Web Audio API overview (Part 2 of 2)

In the first part, we looked at the basics of the Web Audio API and using it to visualize music. In this second part I'll be showing you how to implement a LowPass Filter and gain control in our example from the first part. We'll add some colour to it too.

Let's start with the easiest bit, the color. To change the color of the bars, all you need to do is change ctx.fillStyle = "white"; to whatever color. If you're like me, you won't like single color bars. I think those bars deserve a nice rainbow gradient. This is done very easily:

gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);

gradient.addColorStop(0, "rgba(255, 0, 0, 1)");
gradient.addColorStop(0.15, "rgba(255, 255, 0, 1)");
gradient.addColorStop(0.3, "rgba(0, 255, 0, 1)");
gradient.addColorStop(0.5, "rgba(0, 255, 255, 1)");
gradient.addColorStop(0.65, "rgba(0, 0, 255, 1)");
gradient.addColorStop(0.8, "rgba(255, 0, 255, 1)");
gradient.addColorStop(1, "rgba(255, 0, 0, 1)");

ctx.fillStyle = gradient;

And that's it now we've a nice gradient.

Next up, gain. You can create one just like an analyser:

source = audioContext.createMediaElementSource(audioElement);
gain = audioContext.createGainNode();
analyser = audioContext.createAnalyser();

source.connect(gain);
gain.connect(analyser);
analyser.connect(audioContext.destination);

Now we have a GainNode, but no way for the user to interact with it.

To give the user some control over the gain, we'll have a well-known input.


<p>Gain: <input id="gain" type="range" value="1" min="0" max="1" step="0.01"></p>

The reason it has a max value of 1 is that the GainNode by default sets this value (It is possible to change this). Of course an input alone doesn't do anything. We'll add an event listener to it:

document.getElementById("gain").addEventListener('change',
  function(e){
  gain.gain.value = this.value
});

This snippet sets gain.gain.value to the value on the input. And that is all there is to it.

Adding a LowPass filter is the same procedure.

  1. Add an input box.
  2. Create the LowPass filter in Javascript.
  3. Add a binding between input and LowPass filter

Here is the source code:


<p>LowPass: <input id="lowpass" type="range" value="5000" min="0" max="5000" step="10"></p>

<script>
function init() {
  source = audioContext.createMediaElementSource(audioElement);
  gain = audioContext.createGainNode();
  filter = audioContext.createLowPass2Filter();
  filter.cutoff.value = 22050;
  analyser = audioContext.createAnalyser();
  source.connect(gain);
  gain.connect(filter);
  filter.connect(analyser);
  analyser.connect(audioContext.destination);
  draw();
}


document.getElementById("lowpass").addEventListener('change',
  function(e){
    filter.cutoff.value = this.value
});


</script>

In this short series I have demonstrated how easy it is to work with the Web Audio API. You now know how to create Audio nodes and change their effect on audio.