Web Audio API Cheat Sheet
The raw Web Audio API — the layer under Tone.js and friends. Create a context, wire nodes into a graph, and schedule parameter changes on the audio clock.
Context
const ctx = new AudioContext()Create the audio contextawait ctx.resume()Resume after a user gesture (autoplay policy)ctx.currentTimeThe audio clock, in seconds — schedule against thisctx.destinationThe output node (your speakers)Make a sound
const osc = ctx.createOscillator()Create an oscillatorosc.type = 'sine''sine' | 'square' | 'sawtooth' | 'triangle'osc.frequency.value = 440Frequency is an AudioParam, so set .valueosc.connect(ctx.destination)Wire it to the outputosc.start(); osc.stop(ctx.currentTime + 1)Start now, stop in one secondGain & routing
const gain = ctx.createGain()Create a gain (volume) nodegain.gain.value = 0.3The AudioParam is called .gainosc.connect(gain).connect(ctx.destination)connect() returns the target, so calls chainnode.disconnect()Unwire a nodeParameter automation
p.setValueAtTime(v, t)Jump to a value at time tp.linearRampToValueAtTime(v, t)Ramp linearly to v by time tp.exponentialRampToValueAtTime(v, t)Ramp exponentially (never ramp to exactly 0)g.gain.setValueAtTime(1, ctx.currentTime); g.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.5)A simple decay envelope
Filters & analysis
const f = ctx.createBiquadFilter()Create a filterf.type = 'lowpass'; f.frequency.value = 800Type plus cutoffconst an = ctx.createAnalyser(); an.fftSize = 2048Create an analyser for visualisationconst data = new Uint8Array(an.frequencyBinCount); an.getByteFrequencyData(data)Read the spectrum into a byte array
Playing files
const buf = await ctx.decodeAudioData(arrayBuffer)Decode fetched audio into an AudioBufferconst src = ctx.createBufferSource()Create a playback sourcesrc.buffer = buf; src.loop = trueAssign the buffer; optionally loopsrc.connect(ctx.destination); src.start()Play it (a source can only be started once)Web Audio API — The browser's native audio engine.