Making Music with The WebAudio API Part 1

The WebAudio API gives us a way to use JavaScript to make and manipulate audio within a Web page in some very powerful ways. This series of articles demonstrates how we can use WebAudio to synthesize music.

The following example lets a user click a button to play a tone and click another button to stop it.

In this example, the first important thing that happens is creating a new AudioContext. Methods of that object will be used to create other kinds of WebAudio objects and (crucially) it has the .destination property, which is what we connect an output to so that we can hear the sound that we’re creating.

Next, we call the context’s .createOscillator() method to create an OscillatorNode object. That is the object that will produce the tone.

In order to specify what pitch of tone our oscillator will produce, we then set its frequency to 440. The unit of measurement for that value is Hz (oscillations per second) and 440 Hz is the typical reference frequency for a middle A (see Note Frequencies).

You will notice that we do not set the frequency of the oscillator by simply assigning a value to oscillator.frequency. Instead, we assign it to oscillator.frequency.value. That is because oscillator.frequency refers to an AudioParam object (see AudioParam) for the frequency and not to the frequency value itself.

Now that we have a context and a configured oscillator, we need to connect the output of the oscillator to the context’s destination. That is what oscillator.connect( audioCtx.destination ); does.

Before it will produce any sound, the oscillator now needs to be started, so when the user clicks the “Play Tone” button, we make a call to
oscillator.start(). We also enable the “Stop Tone” button.

Finally, when the user clicks the “Stop Tone” button, we call oscillator.stop() to make the oscillator stop producing its tone.

The next article in this series will discuss how to play a note more than once and how to play notes of various musical pitches.