Make Music in the Browser with the Web Audio API
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.
sine. 432 times per second. 65% level.
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.
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
Give a switch two sounds
Switch between On and Off. Both cues use the same two frequencies. Reversing their order makes one rise and the other fall.
Selected On. 650 to 1050 Hz in 75 ms.
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
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.
The copy starts 250 milliseconds after the original.
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.
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.
Your tick returns every 250 ms. About 4 ticks per second.
// 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.
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.
Built-in · Chromium: 4.98 ms. AudioWorklet: 2.31 ms.
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
Web Audio API node reference
Open the Web Audio node map
| What you want to do | Web Audio nodes |
|---|---|
| Make a signal or play audio from memory | OscillatorNode, ConstantSourceNode, AudioBufferSourceNode |
| Bring in media or live audio | MediaElementAudioSourceNode, MediaStreamAudioSourceNode, MediaStreamTrackAudioSourceNode |
| Change volume, tone or dynamics | GainNode, BiquadFilterNode, IIRFilterNode, WaveShaperNode, DynamicsCompressorNode |
| Add delay or apply a recorded impulse response | DelayNode, ConvolverNode |
| Place a sound in space or split and combine channels | StereoPannerNode, PannerNode, ChannelSplitterNode, ChannelMergerNode |
| Inspect the wave or its frequencies | AnalyserNode |
| Send it to the audio device or to a media stream | AudioDestinationNode, MediaStreamAudioDestinationNode |
| Connect your own processor | AudioWorkletNode. The older ScriptProcessorNode is deprecated. |
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.
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 .