Web Audio API

On this page 8

The Web Audio API is a high-level JavaScript interface for generating, processing and analyzing audio inside the browser through a directed graph of connected audio nodes. Among the Web APIs, it is the standard choice when an application needs more than simple playback: precise timing, synthesis, spatial sound, effects or live visualization of a signal.

The specification is maintained by the W3C Audio Working Group and is implemented in all major browser engines. Unlike the HTML audio element, which plays a file from start to end, the Web Audio API exposes the signal itself, so developers can route, mix and transform it with sample-accurate scheduling on the Web platform.

How the audio routing graph works

Every Web Audio application starts with an AudioContext, the object that owns the audio clock, the sample rate and the audio rendering thread. Developers create nodes from the context and connect them with the connect() method, forming a graph that flows from source nodes through processing nodes to a single destination node, normally the system speakers.

The browser renders the graph in fixed blocks called render quanta of 128 sample-frames. At a typical sample rate of 44,100 or 48,000 Hz, one quantum lasts roughly 2.7 to 2.9 milliseconds. This processing runs on a dedicated real-time thread, separate from the main JavaScript thread, which is why audio can keep playing smoothly while the page performs layout or script work.

Nodes expose AudioParam objects, such as gain or frequency, that can be automated over time. Methods such as setValueAtTime(), linearRampToValueAtTime() and setTargetAtTime() schedule changes against the context clock, currentTime, rather than against the less precise timers of the main thread.

Core node types in the Web Audio API

The API ships with a library of built-in nodes implemented natively by the browser, so common processing does not require custom code. The table below groups the most frequently used nodes by role.

NodeRoleTypical use
OscillatorNodeSourceSynthesized tones, test signals
AudioBufferSourceNodeSourceShort decoded samples and sound effects
MediaElementAudioSourceNodeSourceRouting an HTML audio or video element
MediaStreamAudioSourceNodeSourceMicrophone or WebRTC input
GainNodeProcessingVolume control, fades, mixing
BiquadFilterNodeProcessingLow-pass, high-pass and equalizer filters
DynamicsCompressorNodeProcessingLimiting peaks, leveling loudness
ConvolverNodeProcessingReverb from impulse responses
PannerNodeSpatialization3D positioning with HRTF
AnalyserNodeAnalysisFFT spectrum and waveform data
Frequently used audio nodes and their roles

When no built-in node fits, the AudioWorklet interface lets developers write a custom processor in JavaScript or WebAssembly that runs on the audio thread. It replaced the deprecated ScriptProcessorNode, which ran on the main thread and caused glitches whenever the page was busy.

Key parameters and timing behavior

Several context settings determine latency, quality and resource use. Understanding them helps explain why the same code can sound different across devices and operating systems.

ParameterTypical valueWhat it affects
sampleRate44,100 or 48,000 HzFrequency range and CPU cost
Render quantum128 framesGranularity of processing
baseLatencyAbout 3 to 12 msDelay inside the audio pipeline
outputLatencyAbout 10 to 40 msDelay to the physical output
latencyHintinteractive, balanced, playbackTrade-off between latency and stability
statesuspended, running, closedWhether the clock advances
Context parameters that shape audio behavior

The latencyHint option tells the browser whether to prefer low latency for interactive instruments or larger buffers for stable media playback. Actual latency depends heavily on the operating system audio stack and the output device; Bluetooth headphones often add well over 100 milliseconds, which no browser setting can remove.

The Web Audio API overlaps with several neighboring interfaces, and choosing correctly avoids unnecessary complexity. The comparison below positions it against the alternatives a developer is most likely to consider.

TechnologyMain purposeWhen to prefer it
HTML audio elementSimple file playbackPodcasts, music players without effects
Web Audio APISignal processing and synthesisGames, instruments, visualizers, effects
WebRTCReal-time peer communicationVoice and video calls across networks
Media Source ExtensionsAdaptive streamingSegmented streaming with bitrate switching
WebCodecsLow-level encode and decodeCustom codecs and media pipelines
Web Audio compared with alternative approaches

These technologies frequently work together rather than compete. A WebRTC call can feed a MediaStream into a Web Audio graph for noise gating or level metering, and a Canvas API or WebGL scene can draw the frequency data that an AnalyserNode produces.

Practical use and implementation choices

Typical applications include browser games, digital audio workstations, music education tools, podcast editors and audio visualizers. The right architecture depends on what the application needs to do with the signal, as the decision table shows.

RequirementRecommended approachReason
Short sound effectsDecoded AudioBufferInstant, sample-accurate triggering
Long music tracksMedia element sourceStreams without decoding into memory
Custom DSP algorithmAudioWorkletRuns on the audio thread
Rhythmic sequencingLookahead schedulerAvoids main-thread timer jitter
Offline rendering or exportOfflineAudioContextRenders faster than real time
Choosing an approach for common requirements

For sequencers and drum machines, the established technique is a lookahead scheduler: a main-thread timer wakes every 25 milliseconds or so and schedules notes slightly ahead on the audio clock. This combines the precision of the audio clock with the flexibility of ordinary JavaScript.

Limitations and common mistakes

The most frequent surprise is the autoplay policy. Browsers create an AudioContext in the suspended state unless a user gesture has occurred, so developers must call resume() inside a click or key handler. Other recurring problems are listed below.

  • Reusing source nodes: an AudioBufferSourceNode can be started only once; create a new one for each playback.
  • Creating many contexts: each AudioContext consumes system resources, so one shared context per page is the norm.
  • Abrupt gain changes: setting gain instantly produces audible clicks; short ramps of a few milliseconds prevent them.
  • Relying on setTimeout for timing: main-thread timers drift by tens of milliseconds under load.
  • Ignoring cross-origin rules: media from another origin without CORS headers outputs silence to the graph.

Developers should also remember that heavy AudioWorklet code competes for a strict deadline of under three milliseconds per quantum. Exceeding it produces dropouts and crackles, especially on low-power mobile devices.

Explained without jargon

Think of the Web Audio API as a virtual mixing desk built into the browser. A page can do more than press play. It can plug sound sources, volume knobs, filters and echo units together. It works like cables on a studio rack.

The browser does this work in its own fast lane. So the sound stays smooth even when the page is busy. That is why games, online instruments and music tools react to a click almost instantly. They can play notes exactly on the beat.

A typical use case

A music school builds a browser-based metronome and tuner for students practicing at home. When a student presses Start, the page resumes a single AudioContext and uses a lookahead scheduler that queues short OscillatorNode clicks about 100 milliseconds ahead on the audio clock, keeping the beat steady at 120 beats per minute even while the page animates.

For the tuner, the microphone stream enters the graph through a MediaStreamAudioSourceNode and reaches an AnalyserNode with an FFT size of 4,096. A small routine estimates the dominant pitch about 30 times per second and shows whether a violin string sits above or below 440 Hz. The result is a tool that works on any modern browser without installing an app, with timing accurate to a fraction of a millisecond.