Unlock Powerful Audio Effects with Web Audio API: A Hands‑On Guide
This article introduces the Web Audio API, covering AudioContext, audio nodes, routing graphs, various source types, processing nodes like AnalyserNode and BiquadFilterNode, as well as spatialization with PannerNode and convolution reverb, providing code examples and practical demos for frontend developers.
1. AudioContext
AudioContextprovides a central context for audio processing, acting as a controller for the audio routing graph.
Before processing, create an AudioContext instance that can be shared globally; all audio nodes must belong to the same context.
1.1 Audio Nodes
Audio nodes ( AudioNode) are the basic units of the audio routing graph and depend on an AudioContext.
Each node has inputs and outputs and can be connected via the connect method, e.g., to audioContext.destination for playback.
audioBufferSourceNode.connect(audioContext.destination)Audio nodes fall into three categories:
Source Node – produces audio, only outputs.
Process Node – processes audio, has inputs and outputs.
Destination Node – usually the playback device such as speakers.
Some nodes have multiple outputs, e.g., ChannelSplitterNode, and corresponding inputs like ChannelMergerNode.
1.2 Routing Graph
Web Audio uses a modular API; connecting nodes builds a routing graph controlled by the AudioContext. Example of simple playback:
const ac = new AudioContext();
const $audio = document.querySelector('#audio');
const sourceNode = ac.createMediaElementSource($audio); // audio element source
const gainNode = ac.createGain();
gainNode.gain.value = 0;
$audio.addEventListener('play', () => {
gainNode.gain.exponentialRampToValueAtTime(1, 1);
});
sourceNode.connect(gainNode);
gainNode.connect(ac.destination);2. Audio Sources
Web audio sources include audio elements, network‑loaded files, real‑time streams (WebRTC, microphone), and generated signals such as OscillatorNode.
2.1 Creating a Source from <audio> Tag
Network‑loaded files must be turned into a source node; an <audio> element cannot be connected directly to other nodes.
const ac = new AudioContext();
const $audio = document.querySelector('#audio');
const sourceNode = ac.createMediaElementSource($audio);
sourceNode.connect(/* other audio node */);2.2 Loading Audio Data via HTTP
Fetch binary audio data, decode it, and assign it to a AudioBufferSourceNode:
const ac = new AudioContext();
const source = ac.createBufferSource();
source.connect(ac.destination);
fetch('xxx.mp3')
.then(res => res.arrayBuffer())
.then(async buffer => {
source.buffer = await ac.decodeAudioData(buffer);
source.start();
});The decoded data is stored in an AudioBuffer and assigned to source.buffer. Buffers are suitable for short clips; for long audio, use media element sources.
2.3 Generating Sound with OscillatorNode
OscillatorNodecan generate periodic waveforms of types square, sine, sawtooth, triangle, or custom (default sine). Set its frequency (an AudioParam) via the value property.
const ac = new AudioContext();
const oscillator = ac.createOscillator();
oscillator.type = 'square';
oscillator.frequency.value = 440;
oscillator.connect(ac.destination);
oscillator.start();Custom waveforms can be created with PeriodicWave and applied via setPeriodicWave:
const real = [0, 0, 1, 0, 1];
const imag = [0, 0, 0, 0, 0];
const periodicWave = ac.createPeriodicWave(real, imag);
oscillator.setPeriodicWave(periodicWave);2.4 Audio Streams
Media streams from microphones or WebRTC can be turned into a source node with audioContext.createMediaStreamSource(), enabling simple recording visualizations.
3. Audio Processing
Various processing nodes provide analysis and effects.
3.1 AnalyserNode
AnalyserNodeperforms real‑time FFT, exposing time‑domain and frequency‑domain data.
const analyser = audioContext.createAnalyser();
analyser.fftSize = 2048;
const dataArray = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteTimeDomainData(dataArray);3.2 BiquadFilterNode
BiquadFilterNodeis a digital filter with parameters type, frequency, Q, and gain.
const filter = ac.createBiquadFilter();
filter.type = 'peaking';
filter.Q.value = 1;
filter.frequency.value = 1000;
filter.gain.value = 5;
source.connect(filter);
filter.connect(ac);Filter types include lowpass, highpass, bandpass, lowshelf, highshelf, peaking, notch, and allpass.
3.3 PannerNode
PannerNodeadds 3D spatial audio, supporting Doppler effects. Key properties include position, orientation, and cone angles.
const panner = ac.createPanner();
panner.panningModel = 'HRTF';
panner.distanceModel = 'inverse';
panner.maxDistance = 500;
panner.refDistance = 50;
panner.rolloffFactor = 1;
panner.coneInnerAngle = 360;
panner.orientationX.value = 0;
panner.orientationY.value = 0;
panner.orientationZ.value = 1;
const listener = ac.listener;
listener.forwardX.value = 0;
listener.forwardY.value = 0;
listener.forwardZ.value = -1;
listener.upX.value = 0;
listener.upY.value = 1;
listener.upZ.value = 0;
source.connect(panner);
panner.connect(ac.destination);3.4 ConvolverNode
ConvolverNodeperforms linear convolution with an impulse response (usually a .wav file) to create reverberation effects.
const impulse = ac.decodeAudioData(arrayBuffer);
const convolver = ac.createConvolver();
convolver.buffer = impulse;
source.connect(convolver);
convolver.connect(ac.destination);4. Compatibility
Web Audio support varies across browsers; consult the MDN compatibility table for details.
5. Conclusion
The Web Audio API offers a rich set of features for playback, synthesis, analysis, and spatialization. This article covered basic concepts and demos; further exploration is encouraged.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
