CKTIS / JavaScript
AudioContext: analyse and play audio from a media element
Route an audio or video element through an analyser to the audio output, and manage graph processing separately from the element’s playback.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const ctx = new AudioContext();
const analyser = ctx.createAnalyser();
const source = ctx.createMediaElementSource(mediaElement); // HTMLMediaElement
source.connect(analyser);
analyser.connect(ctx.destination);
// In an async handler for a user action:
await Promise.all([ctx.resume(), mediaElement.play()]);
const state = ctx.state;Call methods on an AudioContext instance, not on the constructor. It inherits createAnalyser(), state, and destination from BaseAudioContext. The no-argument createAnalyser() returns an AnalyserNode that exposes waveform and spectrum data without altering the signal it passes through. For waveform samples, use a Uint8Array of length fftSize; frequencyBinCount counts spectrum bins and is half of fftSize.
createMediaElementSource(element) takes an existing HTMLMediaElement (audio or video), not a URL. It returns a MediaElementAudioSourceNode and reroutes the element’s audio into the graph. Connect source to analyser, then analyser to ctx.destination: this read-only property gives you the AudioDestinationNode, the realtime context’s final output. An analyser can measure without an output connection, but that route is then inaudible. Reuse the source node: binding the same element again throws InvalidStateError, and disconnecting the node does not undo the association.
The no-argument resume() resumes the graph’s clock and processing, not the element’s playback. It returns a Promise that fulfills when the context resumes and rejects if it is closed. OfflineAudioContext.resume() is a separate method for resuming offline rendering. In a real click handler, call both resume() and element.play() before the first await; handle rejections such as NotAllowedError from play(). Use element.pause() to pause the media.
The read-only state describes the context: running means the graph is processing, suspended means it is paused (including by autoplay policy), closed is permanent, and interrupted indicates an external interruption whose handling varies across browsers. Watch statechange; running does not guarantee audible sound. The source node outputs silence for cross-origin media loaded without CORS authorization. For a public cross-origin file, set element.crossOrigin = 'anonymous' before src and configure the server’s CORS headers. These are web platform APIs, not ECMAScript 2024 features; runtime support varies. When done with the context, close() releases its system audio resources.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Play and analyse</title>
</head>
<body>
<button id="play" type="button">Play and analyse</button>
<script>
(() => {
function makeTone() {
const rate = 8000;
const wav = new Uint8Array(44 + rate);
const view = new DataView(wav.buffer);
const text = (offset, value) => wav.set(new TextEncoder().encode(value), offset);
// One second of mono, unsigned 8-bit PCM in a WAV container.
text(0, 'RIFF');
view.setUint32(4, 36 + rate, true);
text(8, 'WAVEfmt ');
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, 1, true);
view.setUint32(24, rate, true);
view.setUint32(28, rate, true);
view.setUint16(32, 1, true);
view.setUint16(34, 8, true);
text(36, 'data');
view.setUint32(40, rate, true);
for (let i = 0; i < rate; i++) {
wav[44 + i] = 128 + Math.round(12 * Math.sin(2 * Math.PI * 440 * i / rate));
}
return new Blob([wav], { type: 'audio/wav' });
}
const button = document.getElementById('play');
button.addEventListener('click', async () => {
button.disabled = true;
const media = new Audio();
let ctx;
let url;
try {
ctx = new AudioContext();
const analyser = ctx.createAnalyser();
analyser.fftSize = 1024;
const source = ctx.createMediaElementSource(media);
source.connect(analyser);
analyser.connect(ctx.destination);
const finished = new Promise((resolve) => {
media.onended = () => resolve(true);
media.onerror = () => resolve(false);
});
url = URL.createObjectURL(makeTone());
media.src = url;
await Promise.all([ctx.resume(), media.play()]);
const samples = new Uint8Array(analyser.fftSize);
analyser.getByteTimeDomainData(samples);
console.log(`state=${ctx.state}; samples=${samples.length}`);
if (!(await finished)) throw new Error('Media failed during playback');
} catch (error) {
console.error(error);
} finally {
media.pause();
media.removeAttribute('src');
media.load();
if (url !== undefined) URL.revokeObjectURL(url);
if (ctx && ctx.state !== 'closed') {
await ctx.close().catch((error) => console.error(error));
}
}
}, { once: true });
})();
</script>
</body>
</html>Result
state=running; samples=1024
Save the example as `index.html` and open it in a browser via a local HTTP server. Open the developer console and click `Play and analyse` on the page. With Web Audio and PCM WAV support, playback permitted, and no interruption, expect a short tone and `state=running; samples=1024`. The WAV is generated locally. The count is the array length, not the number of nonzero samples. Reload to repeat.
Related lessons
- JavaScript · Lesson 34 · Advanced · Version: 4
Sources
- BaseAudioContext: createAnalyser() method
- AudioContext: createMediaElementSource() method
- AudioContext: resume() method
- BaseAudioContext: state property
- BaseAudioContext: destination property
- AnalyserNode
- AnalyserNode: getByteTimeDomainData() method
- OfflineAudioContext: resume() method
- AudioContext: close() method
- Using the Web Audio API
- HTML Living Standard — Media elements: play()
- ECMAScript 2024 Language Specification — Promise.all