Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 122 ยท Web APIs

Web Audio API Basics

Generate and shape sound with AudioContext, oscillators, gain nodes and filters. Build a small synthesizer and draw its waveform with an analyser.

The <audio> element plays files. The Web Audio API is something different: it is a small sound studio built into the browser. You create sound sources (a synthesized tone, a decoded sample, a microphone), connect them through processing nodes (volume, filters, delay, panning) and send the result to the speakers. Games use it for sound effects, music apps for synthesizers, and accessibility tools for audio cues.

The central idea is an audio graph. Every piece is a node, and you wire nodes together with connect() like cables between guitar pedals. This lesson teaches the graph model, then builds a short beep, a controllable synthesizer and a live waveform display.

Browsers refuse to make sound until the user has interacted with the page. Create or resume the AudioContext inside a click or key handler, otherwise it stays in the "suspended" state and nothing is audible. Remember to keep volume low when testing with headphones.

The audio graph

flowchart LR
  A["OscillatorNode<br/>(source)"] --> B["BiquadFilterNode<br/>(effect)"]
  B --> C["GainNode<br/>(volume)"]
  C --> D["AudioContext.destination<br/>(speakers)"]

Sound flows from a source, through effects, to the destination.

Everything lives inside an AudioContext. It holds the graph, owns the clock (audioContext.currentTime, in seconds, a very precise timer) and exposes the output as audioContext.destination.

JavaScript
const audioContext = new AudioContext();

Some common nodes:

Node Created with Does
Oscillator createOscillator() Generates a repeating wave: sine, square, sawtooth, triangle
Gain createGain() Multiplies the signal: a volume control
Biquad filter createBiquadFilter() Low-pass, high-pass, band-pass and other filters
Stereo panner createStereoPanner() Moves sound left or right (pan from -1 to 1)
Delay createDelay() Delays the signal, useful for echoes
Analyser createAnalyser() Gives you waveform and frequency data for visuals
Buffer source createBufferSource() Plays decoded audio data, such as a sound effect

Your first beep

An oscillator plays until you stop it, and it can be started only once. Create a new one for every note, because oscillators are cheap.

Play a beep

connect() returns the node you connected to, so chains such as a.connect(b).connect(c) read left to right. Always schedule start and stop times from audioContext.currentTime rather than relying on setTimeout, whose timing is loose.

AudioParam: values that change over time

Properties such as frequency and gain are not plain numbers. They are AudioParam objects, and they can be scheduled with sample-accurate precision:

JavaScript
const now = audioContext.currentTime;
gain.gain.setValueAtTime(0, now);                       // start silent
gain.gain.linearRampToValueAtTime(0.3, now + 0.02);     // fast fade in
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.6); // fade out

This is how you avoid the sharp "click" you hear when a tone starts or stops abruptly at a non-zero value. A short envelope (attack and release) makes notes sound polished. Note that exponential ramps cannot reach exactly 0, so ramp to a tiny value such as 0.001.

A tiny synthesizer

Now combine the pieces: a row of keys that play notes with an envelope, a wave-type menu and a volume slider. Each key's frequency comes from a formula: every semitone multiplies the frequency by 2^(1/12), so a note n semitones above A4 (440 Hz) is 440 * 2 ** (n / 12).

Mini synthesizer

Notice the two gain nodes: env shapes each note, while master is the shared volume. Splitting responsibilities like this is the heart of the graph model.

Filters

A BiquadFilterNode removes parts of the frequency spectrum. A lowpass filter keeps low frequencies and softens bright, buzzy sounds, which is why a sawtooth wave through a low-pass filter sounds "warm".

JavaScript
const filter = audioContext.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.value = 800;   // cutoff in Hz
filter.Q.value = 5;             // resonance
oscillator.connect(filter).connect(gain).connect(audioContext.destination);

Because frequency is an AudioParam, you can sweep it with linearRampToValueAtTime() for the classic "wah" effect.

Seeing the sound with AnalyserNode

An AnalyserNode taps the signal without changing it and gives you the current waveform or spectrum. Drawing it on a canvas is a great way to see what your graph does.

Draw the waveform

Drag the slider and watch the wave get denser as the pitch goes up. setTargetAtTime() glides smoothly to the new value instead of jumping, which avoids clicks.

Playing sound files

For recorded effects, fetch the file, decode it into an AudioBuffer, and play it through a buffer source. Sources are one-shot like oscillators, so create a new one per playback.

JavaScript
const response = await fetch("/samples/media/chime.mp3");
const buffer = await audioContext.decodeAudioData(await response.arrayBuffer());

function playChime() {
  const source = audioContext.createBufferSource();
  source.buffer = buffer;
  source.connect(audioContext.destination);
  source.start();
}

Decoding once and reusing the buffer is much faster and more precisely timed than creating a new <audio> element for each effect. For long music, a plain <audio> element is simpler and streams from the network; you can still route it into the graph with audioContext.createMediaElementSource(audioElement).

Good practice

  • Respect user gestures: create and resume the context in a click or key handler, and check audioContext.state.
  • Keep volume modest and never autoplay loud sound. Offer a mute control and give a visual alternative for anything meaningful, as covered in Accessibility Basics.
  • Free resources: stop and disconnect nodes you no longer need, and call audioContext.close() when finished. Browsers limit the number of live contexts.
  • Prefer AudioParam scheduling to assigning .value repeatedly when you need smooth changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a Web Audio oscillator not be restarted after you call stop()?

    Oscillator and buffer source nodes can be started only once. They are cheap, so create a fresh one for every sound.
  2. 2. What should you do if audioContext.state is "suspended" after creation?

    Autoplay policies keep contexts suspended until the user interacts. Resume it in a click or key handler.
  3. 3. What does connecting nodes with a.connect(b).connect(audioContext.destination) express?

    connect() wires the output of one node to the input of the next, and returns the destination so you can keep chaining.
  4. 4. Why ramp the gain at the start and end of a note?

    A sudden jump in level creates a click. A short attack and release (an envelope) smooths the note.

Summary

  • The Web Audio API is a graph of nodes inside an AudioContext: sources, effects and the final destination.
  • Create or resume the context after a user gesture; sources such as OscillatorNode are one-shot.
  • GainNode controls volume, BiquadFilterNode shapes tone, AnalyserNode exposes data for visuals.
  • Properties like frequency and gain are AudioParams you can schedule precisely for envelopes and glides.
  • Decode sound files once with decodeAudioData() and play them through new buffer sources.

Next lesson: Speech Synthesis and Speech Recognition, where the browser talks and listens.