2 min read

Web Audio API

The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning), and much more.

1. The Audio Context

Everything happens within an AudioContext. It represents an audio-processing graph built from audio modules linked together, each represented by an AudioNode.

const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

Note: Browsers require a user gesture (click, tap) to resume or start the AudioContext to prevent auto-playing audio annoyances.

document.querySelector('button').addEventListener('click', function() {
  audioCtx.resume().then(() => {
    console.log('Playback resumed successfully');
  });
});

2. Audio Nodes

The API uses a modular routing metaphor. You create nodes and connect them together.

  • Source Nodes: Where sound comes from (e.g., OscillatorNode, AudioBufferSourceNode, MediaElementAudioSourceNode).
  • Effect Nodes: Modify the sound (e.g., GainNode (volume), BiquadFilterNode, DelayNode, ConvolverNode).
  • Destination Node: Where the sound goes (usually the speakers). Accessed via audioCtx.destination.

3. The Audio Graph

You connect nodes using the .connect() method.

Source -> Effect -> Destination

// Create an oscillator (source)
const oscillator = audioCtx.createOscillator();

// Create a gain node (volume)
const gainNode = audioCtx.createGain();

// Connect oscillator to gain node
oscillator.connect(gainNode);

// Connect gain node to destination (speakers)
gainNode.connect(audioCtx.destination);

4. Basic Example: Playing a Tone

const audioCtx = new (window.AudioContext || window.webkitAudioContext)();

function playTone() {
  const oscillator = audioCtx.createOscillator();
  const gainNode = audioCtx.createGain();

  oscillator.type = 'sine'; // 'sine', 'square', 'sawtooth', 'triangle'
  oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // 440Hz (A4)

  gainNode.gain.setValueAtTime(0.5, audioCtx.currentTime); // 50% volume

  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);

  oscillator.start();
  oscillator.stop(audioCtx.currentTime + 1); // Stop after 1 second
}

5. Use Cases

  • Games: Sound effects, background music, spatial audio (3D sound).
  • Music Apps: Synthesizers, drum machines, sequencers.
  • Visualizations: Analyzing frequency data to create visual effects.

programming/javascript/vanilla/javascript programming/javascript/vanilla/ajax-fetch programming/javascript/vanilla/promises-async-await