Analyze Live Audio in a Web Audio Graph
This page covers where a StreamAnalyzer runs in a Web Audio graph. What the analyzer produces — frames, quantized reads, updating estimates — is on Realtime and Streaming, and the class and config reference is in JavaScript/TypeScript Streaming and Realtime API. It continues from WebAssembly Guide.
Choosing where the analyzer runs
| Path | Analysis runs on | WASM in the worklet | Use it for |
|---|---|---|---|
SonareStreamAnalyzerNode | Main thread | No | The default for a live graph: no processor to write, no SharedArrayBuffer |
| Custom analyzer worklet | Audio thread | Yes | Analysis that must stay off the main thread and next to your own DSP |
ScriptProcessorNode | Main thread | No | Demos only; the node is deprecated |
Analyze a graph branch
SonareStreamAnalyzerNode runs a StreamAnalyzer against any node in your audio graph. The worklet side only averages the input channels to mono and transfers fixed-size chunks (chunkFrames, default 4096, at least 128); the analyzer itself runs on the main thread, so its frames lag the audio by about one chunk (4096 frames is about 85 ms at 48 kHz). The node has one input and no output.
// analyzer-worklet.ts
import { registerSonareStreamAnalyzerWorkletProcessor } from '@libraz/libsonare/worklet';
registerSonareStreamAnalyzerWorkletProcessor();// main.ts
import { init } from '@libraz/libsonare';
import { SonareStreamAnalyzerNode } from '@libraz/libsonare/worklet';
await init();
await audioCtx.audioWorklet.addModule('/analyzer-worklet.js');
const analyzer = await SonareStreamAnalyzerNode.create(audioCtx, {
config: { nMels: 64 },
});
source.connect(analyzer.node);
const stopFrames = analyzer.onFrames((frames) => draw(frames.mel, frames.nFrames));
const stopStats = analyzer.onStats((stats) => console.log(stats.estimate.bpm));
// Later:
stopFrames();
stopStats();
await analyzer.destroy();config takes the same fields as new StreamAnalyzer(...). sampleRate defaults to the context's, and any other value throws RangeError. onFrames delivers the readFrames format, and onStats fires when the key or tempo estimate was re-estimated. If a chunk is dropped or the processor restarts, the analyzer's sample offset is reset rather than splicing the two streams together.
Basic Example
ScriptProcessorNode is deprecated
The example below uses createScriptProcessor() because it is the shortest way to see frames flowing. The node runs on the main thread and can glitch under load. For anything real, use SonareStreamAnalyzerNode or a custom analyzer worklet.
import { init, StreamAnalyzer } from '@libraz/libsonare';
async function setupStreaming() {
await init();
const audioCtx = new AudioContext();
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const source = audioCtx.createMediaStreamSource(stream);
// Create analyzer with output-frame throttling
const analyzer = new StreamAnalyzer({
sampleRate: audioCtx.sampleRate,
nFft: 2048,
hopLength: 512,
nMels: 128,
computeMel: true, computeChroma: true, computeOnset: true,
emitEveryNFrames: 4, // one frame per 4 hops: ~21 frames/s (44100 / 512 / 4), also at 48 kHz
});
const processor = audioCtx.createScriptProcessor(512, 1, 1);
processor.onaudioprocess = (e) => {
const input = e.inputBuffer.getChannelData(0);
analyzer.process(input);
const available = analyzer.availableFrames;
if (available > 0) {
const frames = analyzer.readFrames(available);
updateVisualization(frames);
// BPM/key estimates update as audio arrives
const stats = analyzer.stats();
if (stats.estimate.updated) {
console.log(`BPM: ${stats.estimate.bpm?.toFixed(1)}`);
if (stats.estimate.key !== undefined) console.log(`Key: ${stats.estimate.key?.name}`);
}
}
};
source.connect(processor);
processor.connect(audioCtx.destination);
// Call when the session ends: stop the callback, then release the WASM handle.
return () => {
processor.disconnect();
source.disconnect();
analyzer.destroy();
};
}destroy() releases the analyzer's WASM handle (using works too). An embind handle is never garbage-collected, so release it when the session ends.
Custom analyzer worklet
Run StreamAnalyzer inside your own AudioWorkletProcessor when the analysis has to stay off the main thread. Only the small, already-computed frame buffer crosses the thread boundary through postMessage, never raw audio.
The worklet needs its own WASM module
A worklet has its own global scope and its own WASM heap, and it cannot fetch. Inside an AudioWorkletGlobalScope, init() without a moduleFactory is refused with NotSupported. Import the module factory from @libraz/libsonare/module and the classes from @libraz/libsonare/worklet, fetch the .wasm bytes on the main thread, pass them in through processorOptions, and call init({ moduleFactory, wasmBinary }).
This example is for visualization, not hard realtime
readFrames() creates new typed arrays, stats() creates an object and postMessage allocates, all inside process(). That is acceptable for a visualizer that tolerates an occasional glitch, but it is exactly what Realtime safety lists as forbidden in an audio callback. For work that must never glitch, run the analysis on the main thread with SonareStreamAnalyzerNode.
analyzer-worklet.ts:
import moduleFactory from '@libraz/libsonare/module';
import { init, StreamAnalyzer } from '@libraz/libsonare/worklet';
class AnalyzerWorklet extends AudioWorkletProcessor {
private analyzer?: StreamAnalyzer;
private frameCounter = 0;
constructor(options: AudioWorkletNodeOptions) {
super();
const { wasmBinary } = options.processorOptions;
void init({ moduleFactory, wasmBinary }).then(() => {
// sampleRate is a global in AudioWorkletGlobalScope
this.analyzer = new StreamAnalyzer({
sampleRate,
nFft: 2048,
hopLength: 512,
nMels: 64, // reduced for bandwidth
computeMel: true, computeChroma: true, computeOnset: true,
emitEveryNFrames: 4,
});
});
this.port.onmessage = (e) => {
if (e.data.type === 'destroy') {
this.analyzer?.destroy();
this.analyzer = undefined;
}
};
}
process(inputs: Float32Array[][]): boolean {
const input = inputs[0]?.[0];
if (!input || input.length === 0 || !this.analyzer) return true;
this.analyzer.process(input);
const available = this.analyzer.availableFrames;
if (available >= 4) {
const frames = this.analyzer.readFrames(available);
// Transfer buffers for zero-copy
this.port.postMessage({ type: 'frames', data: frames }, [
frames.timestampsSec.buffer, frames.mel.data.buffer, frames.chroma.data.buffer,
]);
}
// Periodically send stats
if (++this.frameCounter % 100 === 0) {
this.port.postMessage({ type: 'stats', data: this.analyzer.stats() });
}
return true;
}
}
registerProcessor('analyzer-worklet', AnalyzerWorklet);main.ts:
import wasmUrl from '@libraz/libsonare/wasm?url';
import processorUrl from './analyzer-worklet.ts?worker&url';
const audioCtx = new AudioContext();
await audioCtx.audioWorklet.addModule(processorUrl);
// `?url` and `?worker&url` are how Vite imports an asset URL; use your bundler's equivalent.
const wasmBinary = await (await fetch(wasmUrl)).arrayBuffer();
const workletNode = new AudioWorkletNode(audioCtx, 'analyzer-worklet', {
processorOptions: { wasmBinary },
});
workletNode.port.onmessage = (e) => {
if (e.data.type === 'frames') {
renderVisualization(e.data.data);
} else if (e.data.type === 'stats') {
updateBpmDisplay(e.data.data.estimate);
}
};
// Connect audio source
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const source = audioCtx.createMediaStreamSource(stream);
source.connect(workletNode);
// Later: release the analyzer inside the worklet.
workletNode.port.postMessage({ type: 'destroy' });Related
- Realtime and Streaming — frames, quantized reads, and updating estimates
- JavaScript/TypeScript Streaming and Realtime API —
StreamAnalyzertypes and the worklet engine facade - Realtime safety — what an audio callback may and may not do