Introduction to the Web Audio API

•

Mon Mar 20 2023

•

5 min read

When building web applications, we may need to build some features around the audio track. This can be tricky, but imagine having access to audio creation, editing, and processing right in your web browser. The Web Audio API makes it possible, allowing you to create interactive audio experiences.

In this guide, we'll walk you through the basics of Web Audio API and demonstrate how you can begin developing your own web audio projects.

Web Audio API

The Web Audio API is a Web API that allows you to generate, edit, and manipulate audio files without the need for external software. The API is based on the idea of an audio graph, which is a collection of audio nodes connected to form a processing pipeline.

The AudioContext is the main component of the Web Audio API, acting as a hub for creating and managing all of the various audio elements known as nodes. These nodes can be audio sources like music or sound effects, or they can be processing components like filters and effects.

Audio sources are represented by AudioBufferSourceNodes. Whereas AudioNodes are used to represent different types of processing components, like volume controls, reverb, or equalizers. Both of these are interfaces exposed by the Web Audio API.

Setting Up Your Environment

To ensure that you have everything you need, you must first set up your development environment. Here are the main steps to follow:

STEP #1

Create a folder and open it in your preferred code editor. Then create an HTML file index.html inside the directory. Please write the basic HTML boilerplate. You can also use the following code snippet:

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Audio API</title>
</head>
<body>
<script></script>
</body>
</html>

Go ahead and copy the above code and paste it into your file.

STEP #2

Let’s create an instance of the Web Audio API and see what we will get after logging it on the console.

html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Web Audio API Test</title>
</head>
<body>
<h1>Web Audio API Test</h1>
<script>
// Initialize the AudioContext
const audioContext = new AudioContext();
// Log the AudioContext to the console
console.log(audioContext);
</script>
</body>
</html>

Go ahead and open this HTML file in your web browser. Now open the developer tools and navigate to the Console section. Here, you will see something like below:

If you see any errors, double-check your setup and ensure you have correctly included the Web Audio API library.

Manipulating Sounds using Web Audio API

Let’s now take a look at how to create audio sources, manipulate audio parameters, and play and stop audio using the API.

Create sound from scratch

The Web Audio API includes a variety of audio generators, such as oscillators and noise sources, that can be used to create sound from scratch. The first thing you should do is to create an AudioContext object and an oscillator node before diving into generating any sound.

We will connect the oscillator to the AudioContext's destination node and generate the sound.

js
// create AudioContext
const audioContext = new AudioContext();
// create oscillator node
const oscillator = audioContext.createOscillator();
// connect oscillator to destination node
oscillator.connect(audioContext.destination);
// set oscillator type and frequency
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(880, audioContext.currentTime);
// start oscillator
oscillator.start();

The above code creates an OscillatorNode that generates a sine wave at a frequency of 880 Hz.

Test the created sound

When the button is clicked, the oscillator starts playing, and the sound is heard.

Let’s now create a button that, when clicked, starts the oscillator so we can hear the sound.

html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Play Audio Button Example</title>
</head>
<body>
<button id="play-button">Play Audio</button>
<script>
const audioContext = new AudioContext();
const oscillator = audioContext.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(880, audioContext.currentTime);
oscillator.connect(audioContext.destination);
const playButton = document.getElementById('play-button');
playButton.addEventListener('click', () => {
oscillator.start();
});
</script>
</body>
</html>

You can change the oscillator's frequency, type, and other parameters to create different sounds.

Similarly, you can also load and play an audio file. To do this, we first need to fetch the file and decode it using the AudioContext's decodeAudioData() method. Once the audio data is decoded, we can create an AudioBufferSourceNode and connect it to the AudioContext's destination node.

Lastly, we can then start the buffer source node to begin playing the audio.

html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Play Audio File</title>
</head>
<body>
<button id="play-button">Play Audio</button>
<script>
const audioContext = new AudioContext();
const playButton = document.getElementById('play-button');
playButton.addEventListener('click', () => {
fetch('./audio.mp3')
.then(response => response.arrayBuffer())
.then(audioData => {
audioContext.decodeAudioData(audioData, buffer => {
const bufferSource = audioContext.createBufferSource();
bufferSource.connect(audioContext.destination);
bufferSource.buffer = buffer;
bufferSource.start();
});
});
});
</script>
</body>
</html>

We have created a button element with an ID of 'play-button' and added a click event listener to it. When the button is clicked, the audio file is fetched, decoded, and played. Please make sure you replace 'audio.mp3' with the actual URL or relative path to the audio file you want to play.

Support

The Web Audio API has good browser support, with the exception of Internet Explorer. Most modern browsers, including Chrome, Firefox, Safari, and Microsoft Edge, support the API.

Wrap up

The Web Audio API provides a powerful toolkit for creating and playing audio in web apps. It is easy to use and provides a vast range of functionalities for creating and manipulating audio.

If you want to learn more about different Web APIs, we have a whole category that you can explore. If you want to learn about animations, we have written an interactive guide on Web Animation API that you can read.