How to use web audio API using JavaScript

What is the web audio API?

The Web Audio API provides a powerful and versatile system to control audio on the web. This APIApplication Programming Interface allows you to manipulate an audio stream on the web.

It can be used to add effects and filters to an audio source on the web. The audio source can be from the <audio>, video/audio source files, or an audio network stream.

Code

Let’s look at an example.

Explanation

  • This example channels the audio from an <audio> element to an AudioContext.

  • Sound effects (like panning) are added to the audio source before being channeled to the speakers’ audio output.

  • The Init button calls the init function when clicked. This will create an AudioContext instance and set it to audioContext.

  • Next, it creates a media source, createMediaElementSource(audio), and passes the audio element as the audio source.

  • The volume node volNode is created using createGain. Here, we adjust the volume of the audio.

  • Next, the panning effect is set using the StereoPannerNode.

  • Finally, the nodes are connected to the media source.

  • The buttons (Play, Pause, Stop) play, pause and stop the audio.

  • We have a volume and panning range slider. If these are changed, the volume and the panning effect of the audio are affected.

References
  • Try out this example of an API that synthesizes and adds effects to audio.
  • Click here for another example.

Free Resources

Attributions:
  1. undefined by undefined