Build a synthesizer in JavaScript with the Web Audio API
This tutorial builds a small polyphonic synthesizer that runs in the browser with no libraries: oscillators, a low-pass filter, ADSR envelopes, voice allocation with stealing, a sustain pedal, and input from a MIDI keyboard through the Web MIDI API. The code is one module of about 150 lines, and the demo below runs exactly that code.
Try it
Click or touch the keys, or turn on computer-keyboard playing (A W S E D F T G Y H U J K: one octave from C4; Z and X shift the octave). Connect a MIDI keyboard with the button.
Sound starts on your first key press (browsers only allow audio after a click or tap).
The signal path
Each note gets its own small chain of audio nodes: an OscillatorNode makes the tone, a BiquadFilterNode set to low-pass softens it, and a GainNode shapes its volume over time (the envelope). All the voices feed one master gain, which feeds the speakers. Oscillators can only be started once, so a voice is created on note-on and thrown away after its release. Creating nodes is cheap; browsers handle hundreds per second.
Pitch comes from the MIDI note number with the equal-temperament formula, where note 69 is A4 at 440 Hz:
/** Equal-tempered frequency of a MIDI note: A4 (note 69) = 440 Hz, 12 notes per octave. */
export const midiToFrequency = (note, a4 = 440) => a4 * 2 ** ((note - 69) / 12);
ADSR envelopes
An envelope moves the voice’s gain through four stages: attack (rise to the peak), decay (fall to the sustain level), sustain (hold while the key is down) and release (fade after the key is let go). Web Audio schedules these ramps on the audio clock, so they are sample-accurate even if the page is busy.
/**
* Attack–decay–sustain on an AudioParam (normally a GainNode's gain), starting at time t in seconds.
* Ramps are scheduled ahead on the audio clock, so they stay sample-accurate whatever the main thread is doing.
*/
export function startEnvelope(param, t, { attack, decay, sustain }, peak = 1) {
param.cancelScheduledValues(t);
param.setValueAtTime(0, t);
param.linearRampToValueAtTime(peak, t + attack);
param.linearRampToValueAtTime(peak * sustain, t + attack + decay);
}
/**
* Release: hold whatever value the envelope has reached at t, then fade to silence.
* cancelAndHoldAtTime avoids a click when a note is released during its attack or decay.
* Returns the time the voice falls silent, so the oscillator can be stopped then.
*/
export function releaseEnvelope(param, t, release) {
if (typeof param.cancelAndHoldAtTime === 'function') param.cancelAndHoldAtTime(t);
else {
param.cancelScheduledValues(t);
param.setValueAtTime(param.value, t);
}
param.linearRampToValueAtTime(0, t + release);
return t + release;
}
The release is where most hand-written synths click. If a key is released during the attack, the gain is somewhere in the middle of a ramp; cancelling the ramp and starting a new one from a stale value makes the level jump. cancelAndHoldAtTime freezes the gain at its exact current value first. Firefox did not support it for a long time, so the code falls back to setting the last known value.
Polyphony and voice stealing
A synth needs to know which notes are sounding, so a note-off can find its voice, and it needs a limit, so a held sustain pedal plus a fast run cannot create hundreds of voices. When the limit is reached, the oldest note is stolen: it gets a 5 ms release so it does not click, and the new note takes its place. Pressing a key that is still sounding replaces that voice, the way most hardware synths behave.
/**
* Keeps track of which notes are sounding. When every voice is busy, the oldest note is "stolen"
* so a new note always plays. Re-pressing a note that is still sounding replaces it.
*/
export function createVoicePool(maxVoices = 8) {
const active = new Map(); // note → voice, in start order (Map keeps insertion order)
return {
allocate(note) {
let stolen = null;
if (active.has(note)) {
stolen = active.get(note);
active.delete(note);
} else if (active.size >= maxVoices) {
const [oldestNote, oldest] = active.entries().next().value;
active.delete(oldestNote);
stolen = oldest;
}
const voice = { note };
active.set(note, voice);
return { voice, stolen };
},
release(note) {
const voice = active.get(note) ?? null;
active.delete(note);
return voice;
},
notes: () => [...active.keys()],
clear() {
const all = [...active.values()];
active.clear();
return all;
},
};
}
Putting it together
/** Oscillator → low-pass filter → gain (envelope) per voice, all voices into one master gain. */
export function createSynth(ctx, options = {}) {
const settings = {
maxVoices: 8, wave: 'sawtooth', cutoff: 2400, attack: 0.01, decay: 0.25, sustain: 0.6, release: 0.35, volume: 0.25,
...options,
};
const master = ctx.createGain();
master.gain.value = settings.volume;
master.connect(ctx.destination);
const pool = createVoicePool(settings.maxVoices);
let pedal = false;
const held = new Set(); // notes released while the sustain pedal was down
function silence(voice, t, release) {
if (!voice?.amp) return;
const end = releaseEnvelope(voice.amp.gain, t, release);
voice.osc.stop(end + 0.02);
}
function noteOn(note, velocity = 100, t = ctx.currentTime) {
const { voice, stolen } = pool.allocate(note);
silence(stolen, t, 0.005); // a very short release, so a stolen voice does not click
held.delete(note);
const osc = ctx.createOscillator();
osc.type = settings.wave;
osc.frequency.setValueAtTime(midiToFrequency(note), t);
const filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(settings.cutoff, t);
const amp = ctx.createGain();
amp.gain.value = 0;
osc.connect(filter).connect(amp).connect(master);
startEnvelope(amp.gain, t, settings, (velocity / 127) ** 1.5); // a curve feels more natural than linear velocity
osc.start(t);
Object.assign(voice, { osc, filter, amp });
return voice;
}
function noteOff(note, t = ctx.currentTime) {
if (pedal) return void held.add(note);
silence(pool.release(note), t, settings.release);
}
function setPedal(down, t = ctx.currentTime) {
pedal = down;
if (down) return;
for (const note of held) silence(pool.release(note), t, settings.release);
held.clear();
}
function allNotesOff(t = ctx.currentTime) {
pedal = false;
held.clear();
for (const voice of pool.clear()) silence(voice, t, 0.02);
}
return { noteOn, noteOff, setPedal, allNotesOff, settings, notes: pool.notes };
}
Velocity is mapped through a curve ((velocity / 127) ** 1.5) rather than linearly, because a linear velocity-to-gain map sounds too loud at soft playing. The sustain pedal does not stop note-offs from arriving; it remembers them and releases those notes when the pedal comes up.
Playing it from a MIDI keyboard
/** Routes raw Web MIDI bytes to the synth: notes, sustain pedal (CC 64) and All Notes Off (CC 120/123). */
export function handleMidi(synth, [status, data1, data2], channel = null) {
const type = status & 0xf0;
if (channel !== null && (status & 0x0f) !== channel - 1) return;
if (type === 0x90 && data2 > 0) synth.noteOn(data1, data2);
else if (type === 0x80 || type === 0x90) synth.noteOff(data1); // note on with velocity 0 means note off
else if (type === 0xb0 && data1 === 64) synth.setPedal(data2 >= 64);
else if (type === 0xb0 && (data1 === 120 || data1 === 123)) synth.allNotesOff();
}
Two details catch people out. A note-on with velocity 0 means note-off, and many keyboards send that instead of a real note-off message. And CC 64 values of 64 and above mean the pedal is down, not only 127. To connect the browser to a keyboard, request access and attach this handler to every input; the Web MIDI API tutorial covers permissions and hot-plugging, and its watchInputs helper is what the demo uses:
const access = await navigator.requestMIDIAccess();
const synth = createSynth(new AudioContext());
for (const input of access.inputs.values()) input.onmidimessage = (e) => handleMidi(synth, e.data);
Starting audio
Browsers create an AudioContext in the “suspended” state until the user interacts with the page. Create or resume() it inside a click, key or touch handler, as the demo does on the first key press, or you will hear nothing and see no error.
Where to go next
- Latency and timing: notes here play “now”. To play a sequence in time, schedule ahead on the audio clock as shown in Web Audio scheduling and timing.
- Pitch bend: multiply the oscillator frequency by
2 ** (semitones / 12). The pitch bend calculator converts the 14-bit MIDI value to semitones. - Richer sound: detune two oscillators a few cents apart, or modulate the filter cutoff with its own envelope.
- Heavier DSP: custom oscillators or effects belong in an
AudioWorklet, which runs your code on the audio thread.
The module is poly-synth.mjs (MIT). Its voice pool, envelopes and MIDI routing are covered by automated tests that run against a recorded fake AudioContext.