The Web Audio API: Graphs, Nodes, and Scheduling
The audio element plays files. The Web Audio API builds sounds. That distinction is the whole point: instead of handing a URL to a player, you construct a directed graph of processing nodes â oscillators, gain stages, filters, analyzers â connected into a destination, and you schedule parameter changes against a high-resolution audio clock. The result is everything the element cannot do: synthesized tones, real-time effects, precise musical sequencing, frequency analysis for visualizers, and spatialization in 3D.
The API has a learning curve driven by two unfamiliar ideas: sound is a graph you wire, not a file you start, and time is expressed in seconds relative to an AudioContext's own clock rather than in milliseconds since page load. Internalize those and the rest is a catalogue of node types.
The Graph Model
An AudioContext owns everything. Inside it, nodes fall into three roles. Source nodes generate or receive audio: oscillators, buffer players, microphone inputs, media element taps. Processing nodes transform it: filters, delay lines, convolvers, waveshapers, dynamics compressors. Destination nodes represent the speakers, and every audible path must eventually reach context.destination. Gain nodes are the connective tissue â they let you fade, mix, and mute branches of the graph without touching the nodes themselves.
Connections are one-way and fan out freely: one output can feed many inputs, and one input can receive many outputs, with the browser summing them. Disconnected nodes simply stop producing sound for that path, which is how you mute a branch without destroying it.
Context State and the Autoplay Policy
Browsers start every AudioContext in a suspended state until a user gesture unlocks audio, an anti-spam measure that catches half of all first implementations of this API:
let context = null;
function ensureContext() {
if (!context) {
context = new (window.AudioContext || window.webkitAudioContext)();
}
if (context.state === 'suspended') {
context.resume();
}
return context;
}
document.getElementById('unlock-audio').addEventListener('click', async () => {
const ctx = ensureContext();
// A silent buffer guarantees the unlock even before any real playback
const silent = ctx.createBuffer(1, 1, ctx.sampleRate);
const source = ctx.createBufferSource();
source.buffer = silent;
source.connect(ctx.destination);
source.start(0);
console.log('Context state:', ctx.state);
});
Create the context lazily inside the first click, keypress, or touch handler rather than at script load, and resume it whenever state reads suspended â including on return from a backgrounded mobile tab, where iOS routinely suspends contexts. Keep a single context per page; constructing many is a resource leak and older Safari versions cap the number you may create.
Synthesis: Oscillators and Envelopes
An oscillator is a source node with a waveform type and a frequency. It plays from the moment you call start, and it must never be restarted â each oscillator instance is single-use, which sounds burdensome until you realize envelopes and one-shot notes are trivially built by creating a short-lived graph per note:
function playNote(frequency, duration, when = 0) {
const ctx = ensureContext();
const start = ctx.currentTime + when;
const osc = ctx.createOscillator();
osc.type = 'triangle';
osc.frequency.setValueAtTime(frequency, start);
const envelope = ctx.createGain();
envelope.gain.setValueAtTime(0.0001, start);
envelope.gain.exponentialRampToValueAtTime(0.4, start + 0.02);
envelope.gain.exponentialRampToValueAtTime(0.0001, start + duration);
osc.connect(envelope);
envelope.connect(ctx.destination);
osc.start(start);
osc.stop(start + duration + 0.05);
return osc;
}
document.getElementById('play-scale').addEventListener('click', () => {
const notes = [261.63, 293.66, 329.63, 349.23, 392.0, 440.0, 493.88, 523.25];
notes.forEach((frequency, index) => playNote(frequency, 0.35, index * 0.22));
});
The exponential ramps deserve attention: gain is perceived logarithmically, so linear fades sound wrong at the quiet end, and exponentialRampToValueAtTime refuses a target of zero â hence the 0.0001 floor. This three-node pattern (oscillator, envelope gain, destination) is the atom of subtractive synthesis; pair it with a lowpass filter between envelope and destination and you have the classic pluck sound in about eight lines.
Playing Recorded Audio
Samples take a different path: fetch the bytes, decode them into an AudioBuffer through the context, then play it through a buffer source node:
async function loadAndPlay(url, when = 0, playbackRate = 1) {
const ctx = ensureContext();
const response = await fetch(url);
if (!response.ok) throw new Error('Sample fetch failed: ' + response.status);
const audioData = await response.arrayBuffer();
const buffer = await ctx.decodeAudioData(audioData);
const source = ctx.createBufferSource();
source.buffer = buffer;
source.playbackRate.value = playbackRate;
const gain = ctx.createGain();
gain.gain.value = 0.8;
source.connect(gain);
gain.connect(ctx.destination);
source.start(ctx.currentTime + when);
return source;
}
Decode once and cache the AudioBuffer: decoding is expensive, and a buffer may be played by many sources simultaneously â the drum-machine pattern of triggering one kick sample forty times per minute is exactly this. decodeAudioData returns a promise in modern browsers; the callback form exists only for ancient Safari.
Filters, Effects, and Composition
Processing nodes chain the same way gain nodes do. A biquad filter exposes type â lowpass, highpass, bandpass, notch and others â and frequency and Q parameters you can automate. A delay line plus a feedback gain makes an echo; a convolver fed with an impulse response file makes a room. A dynamics compressor protects the master output from clipping when many sources stack:
function buildMasterChain(ctx) {
const compressor = ctx.createDynamicsCompressor();
compressor.threshold.value = -18;
compressor.knee.value = 12;
compressor.ratio.value = 4;
const master = ctx.createGain();
master.gain.value = 0.9;
compressor.connect(master);
master.connect(ctx.destination);
return compressor; // sources connect into this
}
Every effect in the chain adds latency only if the browser cannot optimize it away; parallel chains â a dry path plus a wet effect path â are summed automatically at the join node, so a wet-dry mix is two gains, not a special node.
Parameter automation is what turns static effects into expressive ones. AudioParam objects expose setValueAtTime for stepped changes, linear and exponential ramps for curves, and cancelScheduledValues plus setTargetAtTime for interrupting an in-flight automation smoothly â the latter pair is how a filter sweep reverses direction mid-note without a click. Prefer automation methods over assigning .value during playback, because direct assignment snaps the parameter and produces audible zipper noise at anything but the slowest changes.
The Audio Clock: Scheduling That Stays in Time
The naive sequencer â setTimeout every hundred milliseconds â drifts audibly within a minute because timers fire on the main thread's schedule, not the audio hardware's. The correct approach schedules everything against ctx.currentTime ahead of time, letting the audio thread play events with sample accuracy even if the main thread janks:
function scheduleSequence(ctx, notes, stepSeconds) {
const startAt = ctx.currentTime + 0.1;
notes.forEach((note, index) => {
const when = startAt + index * stepSeconds;
scheduleNote(ctx, note.frequency, note.duration, when);
});
return startAt + notes.length * stepSeconds;
}
For music that runs indefinitely, a lookahead scheduler ticks on a coarse timer, reads ahead about a hundred milliseconds, and schedules any notes whose time has come â the pattern behind essentially every serious Web Audio sequencer. Visualizers do the opposite trade: they poll an AnalyserNode on rAF, accepting visual lag because eyes forgive what ears do not.
When Not to Use Web Audio
Do not reach for this API to play a podcast with a play button â the audio element gives you seeking, speed, AirPlay, and the native controls for free, and MediaElementSource can still tap that element into your graph when you want visualization without giving up the element's features. Web Audio earns its complexity when the output depends on synthesis, live processing, or timing that must survive an unstable main thread.
A few operational details round out the picture. Contexts report their sampleRate, usually forty-eight kilohertz on modern systems, which matters when precomputed sample data must match the playback rate. Closing a context frees it for good â call close when tearing down a soundboard page rather than leaving dozens of suspended contexts for the garbage collector. And when debugging silent output, walk the graph backwards from the destination: a muted tab, a gain still at the zero floor from an interrupted envelope, or a filter whose frequency automation ran to zero are the three most common culprits, and each takes seconds to spot in the audio tab of the devtools once you know to look.
Common Mistakes
Creating the AudioContext at page load and leaving it suspended
Fix: Create or resume it inside the first user gesture and check state after every visibility change.
Restarting a single oscillator for repeated notes
Fix: Create one oscillator per note â instances are single-use by design.
Scheduling music with setInterval
Fix: Schedule ahead against ctx.currentTime; timers drift, the audio clock does not.
Decoding the same sample on every trigger
Fix: Decode once into an AudioBuffer and reuse it across buffer sources.
Ramping gain to exactly zero exponentially
Fix: Ramp to 0.0001 â exponential ramps reject a zero target.
Key Takeaways
- Web Audio is a graph of nodes owned by an AudioContext, ending at context.destination.
- Autoplay policy suspends contexts until a user gesture; create and resume lazily.
- Per-note graphs of oscillator, envelope gain, and destination are the atom of synthesis.
- Decode samples once into AudioBuffers and play them with fresh buffer sources each time.
- Schedule musical events against ctx.currentTime with lookahead, never with wall-clock timers.
- Reserve the audio element for plain playback and tap it into the graph only when you need analysis.