Skip to content

Make Music in the Browser with the Web Audio API

A loudspeaker sends two arcs of sound past a code window with one red edit.

Too long, didn’t read. Give a switch its own sound with JavaScript and the Web Audio application programming interface (API). Then turn a series of clicks into a note. Follow the charts with the sound off or jump to the editable melody .

Make your first sound with OscillatorNode

A rising beep can signal On, and a falling one can signal Off. Both cues start with a beep whose pitch you can control.

Compare 216 Hz and 432 Hz in the same window. Hertz counts cycles per second. Twice as many cycles in that window means a higher pitch.

Waveform
Sine · 432 Hz · 65% level4 cycles in view
One cycle · 2.31 ms

sine. 432 times per second. 65% level.

JavaScript excerpt
const ctx = new AudioContext();
const osc = ctx.createOscillator();
const gain = new GainNode(ctx);
osc.type = "sine";
osc.frequency.value = 432;
const level = 65 / 100;
gain.gain.value = 0.18 * level;
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + 0.18);

The AudioContext runs the page’s audio. The OscillatorNode makes a wave one value at a time. Each value is a sample. A GainNode scales those values before they reach the speakers.

OscillatorNode makes a tone. GainNode changes its volume. AudioDestinationNode sends the result to the audio output.

Raise Level to make the same note louder. The peaks get taller. Changing the wave shape gives that note a different sound. The chart draws ideal waves, so sharp corners can sound smoother in playback. OscillatorNode specification

The reference wave completes two cycles while the higher wave completes four in about 9.26 milliseconds.
The reference wave completes two cycles while the higher wave completes four in about 9.26 milliseconds.

Both traces complete four cycles in the same window. The lower-level trace has shorter peaks around the same center line.
Both traces complete four cycles in the same window. The lower-level trace has shorter peaks around the same center line.

Give a switch two sounds

A finger presses a black rocker switch above a small red indicator.
A finger presses a black rocker switch above a small red indicator.

Switch between On and Off. Both cues use the same two frequencies. Reversing their order makes one rise and the other fall.

Pitch over time
On · pitch rises650 → 1,050 Hz

Selected On. 650 to 1050 Hz in 75 ms.

JavaScript excerpt
const wave = ctx.createOscillator();
const pitch = wave.frequency;
const start = ctx.currentTime;
const end = start + 0.075;
// On · 200 Hz from center
pitch.setValueAtTime(650, start);
pitch.linearRampToValueAtTime(
  1050, end
);
wave.connect(gain);
wave.start(start);
wave.stop(end);

The oscillator’s frequency is an AudioParam, a setting you can schedule. The code sets the starting pitch and tells a fresh oscillator when to reach the final one. It reuses ctx and gain from the first beep. Web Audio parameters

The On curve rises from 650 to 1,050 hertz. The Off curve falls from 1,050 to 650 hertz. Both cover 75 milliseconds.
The On curve rises from 650 to 1,050 hertz. The Off curve falls from 1,050 to 650 hertz. Both cover 75 milliseconds.

Add an echo with DelayNode

Send the same sound down two paths to make an echo. Increase Time to the echo and the dashed copy moves farther from the original.

Level over time
OriginalEcho at 250 ms · 40%

The copy starts 250 milliseconds after the original.

JavaScript excerpt
const delay = new DelayNode(ctx);
const echo = new GainNode(ctx);
// DelayNode uses seconds
delay.delayTime.value = 0.25;
echo.gain.value = 0.4;
gain.connect(delay);
delay.connect(echo);
echo.connect(ctx.destination);

One path goes straight to the speakers. The other passes through a DelayNode and its own GainNode, so you can set the wait and level of the echo separately.

One path goes directly from the gain node to the speakers. The other waits in DelayNode, passes through a second gain node and arrives as a quieter echo.

The original sound begins at zero. The dashed trace is a quieter copy that starts 250 milliseconds later.
The original sound begins at zero. The dashed trace is a quieter copy that starts 250 milliseconds later.

A loudspeaker faces a wall. A small red arc suggests an echo coming back.
A loudspeaker faces a wall. A small red arc suggests an echo coming back.

Turn repeating clicks into a note

Line up a series of copies of a click. At four clicks a second, you can hear each one separately. The bracket measures the gap between them.

When each tick starts
250 ms between ticks4 ticks/s
First click Quieter copies

Your tick returns every 250 ms. About 4 ticks per second.

JavaScript excerpt
// 250 ms between clicks
const gapFrames = 12000;
const samples =
  new Float32Array(64800);
let level = 0.13;
for (let frame = 0;
     frame < samples.length;
     frame += gapFrames) {
  samples[frame] = level;
  level *= 0.965;
}

Set Time between ticks to 2.31 ms. That’s about 432 clicks per second, almost the frequency of the higher beep. You’ve tuned a note by setting the gap between clicks.

gapFrames is the number of samples from the start of one click to the start of the next. The excerpt uses one sample per click. Playback uses 14.

The reference tick returns every 250 milliseconds, four times per second. The short target returns every 2.31 milliseconds, around 432 times per second. The two illustrations use different time scales.
The reference tick returns every 250 milliseconds, four times per second. The short target returns every 2.31 milliseconds, around 432 times per second. The two illustrations use different time scales.

When a short feedback loop needs AudioWorklet

The click demo places each copy in advance. A feedback loop makes the next copy by sending each echo back into the delay. Can it return an echo every 2.31 ms?

Play both paths and compare the first echoes with the blue target line. In Chromium, the built-in loop took 4.98 ms. In a feedback loop, a longer gap lowers the note. AudioWorklet reached 2.31 ms.

Wanted first echo · 2.31 ms
Built-in · Chromium4.98 ms · 239 frames
AudioWorklet2.31 ms · 111 frames
First click First echo Target

Built-in · Chromium: 4.98 ms. AudioWorklet: 2.31 ms.

Inside the worklet
const slots = 111; // 432 Hz
const memory =
  new Float32Array(slots);
let slot = 0;
function processSample(input) {
  let echo = memory[slot];
  echo *= 0.965;
  const sample = input + echo;
  memory[slot] = sample;
  slot = (slot + 1) % slots;
  return sample;
}

At 48,000 frames per second, 2.31 ms rounds to 111 frames. One frame holds one sample here. Web Audio 1.0 requires at least 128 frames for a DelayNode in a feedback loop. Web Audio graph rendering rules

AudioWorklet runs custom audio code inside a node. It receives blocks and works through them one sample at a time. Each step reads a slot, turns down its value, mixes in the input and stores the mix in that slot. With 111 slots, the echo returns after 111 samples. AudioWorklet specification

The tick enters a mix that goes to the output and to DelayNode. GainNode weakens the delayed signal before it returns to the mix.The click enters the worklet. It waits in a sample buffer, comes back quieter and joins the input. The mixed sound goes to the speakers.

In the Chromium run, at 432 hertz the built-in loop returns the first echo at 4.98 milliseconds and the worklet at 2.31. At 216 hertz the built-in loop takes 7.29 milliseconds and the worklet takes 4.63.
In the Chromium run, at 432 hertz the built-in loop returns the first echo at 4.98 milliseconds and the worklet at 2.31. At 216 hertz the built-in loop takes 7.29 milliseconds and the worklet takes 4.63.

Web Audio API node reference

Open the Web Audio node map
What you want to doWeb Audio nodes
Make a signal or play audio from memoryOscillatorNode, ConstantSourceNode, AudioBufferSourceNode
Bring in media or live audioMediaElementAudioSourceNode, MediaStreamAudioSourceNode, MediaStreamTrackAudioSourceNode
Change volume, tone or dynamicsGainNode, BiquadFilterNode, IIRFilterNode, WaveShaperNode, DynamicsCompressorNode
Add delay or apply a recorded impulse responseDelayNode, ConvolverNode
Place a sound in space or split and combine channelsStereoPannerNode, PannerNode, ChannelSplitterNode, ChannelMergerNode
Inspect the wave or its frequenciesAnalyserNode
Send it to the audio device or to a media streamAudioDestinationNode, MediaStreamAudioDestinationNode
Connect your own processorAudioWorkletNode. The older ScriptProcessorNode is deprecated.

Web Audio interface index

Write two bars of music

The score lets you choose which note the oscillator plays on each beat. Each column is a beat, with higher notes in the top rows. Pick Rest on beat 2 to leave a space in the melody.

Phrase playback
108 beats/min
Beat 1
Beat 2
Beat 3
Beat 4
Beat 5
Beat 6
Beat 7
Beat 8
Chords Cmaj7Am7

Echo, three quarters of a beat later

Each red note starts an oscillator and fades it through a gain node. The backing carries on through a rest. With Echo on, the previous note can carry into it too. The dashed boxes mark those delayed copies.

You can also turn a hummed phrase into notes with Hum to Melody .