Estimate BPM, Key and Chords Live from a Stream
This page covers the streaming side of libsonare: turning a live audio stream into analysis frames and musical estimates, and the plumbing that streams clip audio and hosts the realtime engine on the audio thread.
StreamAnalyzer— feeds in blocks of audio and emits analysis frames (mel, chroma, onset, spectral) plus musical estimates that update as more audio arrives (BPM, key, chord, chord progression, pattern). Use it for visualizers and live "what is this song doing" displays.- Engine streaming plumbing — the AudioWorklet bridge that runs
RealtimeEngineon the audio thread, paged clip audio streaming for arrangements too large to hold in memory, and the cue-bus output option for monitoring.
If block, latency, or audio thread are unfamiliar, read Realtime Safety first, and Audio Basics for samples and frames — this page assumes that vocabulary. For how blocks, frames, hop and nFft relate, see Streaming analysis.
The short version: use StreamAnalyzer when audio is the input and information is the output. If you are building a UI, it usually feeds graphs, meters, and labels.
Batch vs Streaming
| Approach | Use Case | Latency | Features |
|---|---|---|---|
| Batch | Pre-recorded files | High | All-in-one analysis (BPM, chords, sections) |
| Streaming | Live audio, visualization | Low (one analysis window, ~46 ms at nFft 2048 / 44.1 kHz) | Mel, chroma, onset, updating BPM/key |
Looking for the engine itself?
The RealtimeEngine control surface — transport, parameter automation, MIDI clip scheduling, and external MIDI routing — has its own page, and its lane mixer, group routing, sidechains, and surround buses have another. See Realtime Engine when clips, MIDI, transport, and mixed audio are the output you are building.
In realtime docs, "chunk" or "block" means a short slice of audio processed repeatedly, often inside a Web Audio AudioWorklet — the audio-callback context that runs your DSP on the realtime audio thread, separate from the main/UI thread. Realtime code should avoid heavy allocation inside the audio callback: prepare objects first, then process blocks.
Chunk, block, and frame
Chunks and blocks are short groups of input samples from a realtime stream. Frames are time steps of analysis data produced from those blocks. Think "blocks go in, frames come out" when wiring a UI.
Sample rate and resampling
Sample rate is how many audio samples make one second (44100 and 48000 are common). When a stream's rate does not match what an analyzer expects, the audio must be resampled (rebuilt at the other rate) before processing, which costs extra CPU. StreamAnalyzer analyzes rates up to 44.1 kHz as they are; anything faster (a 48 kHz AudioContext, say) is resampled to 44.1 kHz inside the analyzer by a stateful resampler, so pass the true device rate and let it convert.
What You Will Learn
By the end of this page you should be able to:
- decide whether your app needs
StreamAnalyzer,RealtimeEngine, or the mixing engine; - feed audio blocks without confusing compressed file bytes, decoded samples, blocks, and frames;
- read feature frames for a UI and understand why quantized reads exist;
- use updating estimates without treating early BPM/key/chord values as final answers;
- recognize which realtime operations are safe in an audio callback and which should be prepared outside it.
Which API to use
| If you are building... | Start with |
|---|---|
| A visualizer that draws a spectrogram, chroma, onset strength, or live BPM/key estimate | StreamAnalyzer |
| A live chord / progression / pattern display | StreamAnalyzer.stats() |
| A playback engine with tempo, loop points, markers, metronome, clips, and automation | Realtime Engine |
| A playback engine that also mixes its own tracks live (lanes, buses, sends, strips) | Realtime Engine mixing |
| Sample-accurate MIDI clip playback into engine instruments | Realtime Engine setMidiClips() + sampleAtPpq() |
| The engine on the audio thread, with telemetry | @libraz/libsonare/worklet (AudioWorklet notes) |
| A standalone mixer with strips, sends, and meters (one-shot or scene-driven) | Mixing Engine |
| A simple offline script | Getting Started, not this page |
Runtime entry points
The live callback examples on this page are Browser / WASM. Python has the same block-in, frames-out analyzer, driven from your own loop; the CLI works on whole files.
| Runtime | Entry point | Typical use |
|---|---|---|
| Browser / WASM | StreamAnalyzer, RealtimeEngine, @libraz/libsonare/worklet | Live visualizers, AudioWorklet tools, updating BPM / key / chord displays |
| Node native | StreamAnalyzer | The same analyzer in a server or desktop process |
| Python | StreamAnalyzer(sample_rate=..., ...), RealtimeEngine | Pass blocks, read frames, from your own loop (no AudioWorklet) |
| CLI | sonare analyze, sonare bpm, sonare key, and related commands | File-level checks, batch jobs, JSON output |
For whole-file analysis from Python or the CLI, see Python API or CLI Reference. Treat the WASM / Worklet examples as the source of truth for code that runs inside an audio callback.
StreamAnalyzer
StreamAnalyzer processes blocks and emits frame buffers for UI rendering. It is the right tool for spectrograms, chroma displays, onset-driven visuals, and incremental musical estimates. You construct it once, process() each incoming block, then drain whatever frames have accumulated.
For a first implementation, keep the loop simple:
- create one analyzer with the same
sampleRateas the audio device; - call
process(block)for each decoded or live audio block; - call
readFrames(...)for drawing andstats()for the current musical estimate; - treat early estimates as provisional until several seconds of audio have arrived.
In a browser the analyzer can run on a graph branch, in your own worklet, or (for demos only) in a ScriptProcessorNode; see Streaming Analyzer in the Browser.
The demo below shows the same "audio in, markers out" idea visually: onset detection marks every attack, while beat tracking turns those attacks into a steadier pulse.
Mel, chroma, onset in one line
- Mel — a spectrogram (energy per frequency band over time) on a perceptual pitch scale; good for a "what does this sound like" heatmap.
- Chroma — energy folded into the 12 pitch classes (C, C#, … B); good for showing harmony and key.
- Onset — a strength curve that spikes when a new note or beat starts; useful for visuals that react to beats and tempo.
nFft and hopLength in one line
The analyzer runs an STFT (short-time Fourier transform — repeated FFTs over short, overlapping windows) under the hood.
| Parameter | Meaning | Larger / smaller |
|---|---|---|
nFft | Analysis window size in samples | Bigger = finer frequency detail, coarser timing |
hopLength | How far the window advances between frames | Smaller = more frames per second, more CPU |
The 2048/512 defaults below are the common starting point. See MIR Overview if these are new.
import { init, StreamAnalyzer } from '@libraz/libsonare';
await init();
const analyzer = new StreamAnalyzer({
sampleRate: audioCtx.sampleRate,
nFft: 2048,
hopLength: 512,
nMels: 64,
computeMel: true,
computeChroma: true,
computeOnset: true,
emitEveryNFrames: 4, // throttle: one frame per 4 hops, ~21 frames/s (44100 / 512 / 4), also at 48 kHz
maxPendingFrames: 256, // bound unread output; overflow drops newly produced frames
});
analyzer.process(inputBlock);
const frames = analyzer.readFrames(analyzer.availableFrames);
const stats = analyzer.stats();
if (stats.estimate.updated) {
console.log(stats.estimate.bpm, stats.estimate.key?.name, stats.estimate.chord?.name);
}from libsonare import StreamAnalyzer
analyzer = StreamAnalyzer(sample_rate=48000, n_fft=2048, hop_length=512, n_mels=64)
analyzer.process(block)
frames = analyzer.read_frames(analyzer.available_frames)
stats = analyzer.stats()
if stats.estimate.updated:
print(stats.estimate.bpm, stats.estimate.key.name, stats.estimate.chord.name)Python's stats() returns the same StreamStats with the same estimate level, spelled in snake_case (stats.estimate.bpm, stats.estimate.key.name); the analyzer takes its settings as keyword arguments, and read_quantized_frames_u8 / read_quantized_frames_i16 are the quantized reads.
maxPendingFrames defaults to 4096. Set it to a smaller value for a UI that may pause or fall behind: analysis continues, but newly produced output frames are dropped while the unread queue is full. stats().pendingFrames / stats().droppedOutputFrames report the current backlog and cumulative drops.
Pass the device rate
StreamAnalyzer takes sampleRate as a required option in JavaScript and Python (C++ StreamConfig::sample_rate defaults to 44100 Hz); there is no fallback to the 22050 Hz batch default. Realtime audio arrives straight from the playback/capture graph (AudioWorklet, device callbacks), which almost always runs at 44100/48000 Hz. Rates up to 44.1 kHz are analyzed directly; a 48 kHz stream is resampled to 44.1 kHz inside the analyzer, so pass the true device rate and let it convert. Pass sampleRate: audioCtx.sampleRate so estimates and timestamps line up with what you are actually playing.
Reading frames and output format
A StreamFrames is Structure-of-Arrays: timestamps (timestampsSec), mel, chroma, onset strength, RMS, spectral centroid, spectral flatness, chord root, chord quality, and chord confidence each live in their own typed array. That layout is cheap to slice and cheap to hand to another thread. The mel and chroma fields are Matrix2D values ({ data, rows, cols }). A feature you did not compute is absent, so test the field for undefined before consuming it.
What are spectral centroid and flatness?
Both reduce the shape of one frame's spectrum to a single number you can plot or threshold.
| Measure | Meaning | How to read it |
|---|---|---|
| Spectral centroid | The magnitude-weighted mean frequency of the frame, Σ f·|X| / Σ|X| (magnitude-weighted, not energy-weighted) | Higher sounds "brighter" (more high-frequency content) |
| Spectral flatness | How evenly energy is spread across frequencies | Near 1 is noise-like (energy everywhere at once); near 0 is tonal (energy concentrated in a few strong peaks) |
Together they are a cheap way to describe timbre frame by frame.
For thread transfer and visualization you often do not need full float precision. StreamAnalyzer can quantize the feature arrays, trading precision for bandwidth:
| Read method | Element type | Use it for |
|---|---|---|
readFrames(n) | StreamFrames with Float32Array / Int32Array fields | Full-precision DSP, further analysis |
readFramesI16(n) | StreamFramesI16 with Int16Array fields | Bandwidth-reduced transfer to a worker / over the wire |
readFramesU8(n) | StreamFramesU8 with Uint8Array fields | Cheap visualization (a heatmap pixel only needs 8 bits) |
At nMels = 128 a float frame is about 600 bytes (as a formula, (nMels + 12 + ~8) × 4), a readFramesI16 frame about 300 and a readFramesU8 frame about 150. The integer reads quantize for you, so do not quantize manually before postMessage.
// A spectrogram canvas only needs 8-bit mel — quantize at the source.
const analyzer = new StreamAnalyzer({ sampleRate, nMels: 64 });
analyzer.process(block);
const u8 = analyzer.readFramesU8(analyzer.availableFrames);
// u8.mel is a band-major Uint8Array [nMels x nFrames]: row b, frame f is u8.mel[b * u8.nFrames + f]Match the read method to the consumer
The analyzer always runs in float. Pick readFramesU8 when the data ends up as pixels, readFramesI16 when it crosses a thread/network boundary and you want roughly half the bytes, and readFrames when something downstream does more math.
Plain lists and objects returned from WASM are rooted back into the JavaScript realm that called them. That means arrays from name-list helpers (*Names()), preset-name helpers, section results, key-candidate calls, the object from synthPresetPatch(...), mixer meter snapshots (stripMeter, busMeter), and goniometer samples (readGoniometerLatest) can be passed through structuredClone() or postMessage() without first rebuilding them by hand. Handles with native methods, such as Mixer and StreamAnalyzer, are not cloneable; send their plain data results instead. Typed-array payloads still follow the normal transferable-buffer rules below.
What are "Structure-of-Arrays" and transferable objects?
- Structure-of-Arrays (SoA) means each field lives in its own flat typed array — all timestamps in one array, all mel values in another — instead of an array of per-frame objects. It is cheaper to slice and cheaper to hand to another thread.
- Transferable objects are
ArrayBuffers thatpostMessagecan move to a worker instead of copying. Ownership transfers (the sender's view becomes empty afterward), which makes passing audio frames between threads near-instant. List the buffers in the second argument:postMessage(msg, [buffer, ...]). - Quantizing here means packing each float into a smaller 16-bit or 8-bit integer — fewer bytes to send, at the cost of precision (fine for a meter or heatmap, not for further DSP).
Magnitude frames are not a read path
StreamAnalyzer does not expose per-frame magnitude spectra. There is no readFrames* field for them, so the constructor refuses a computeMagnitude key (like any unknown key, with a TypeError naming it) rather than silently doing nothing. Use mel for a spectrogram view, or run meteringSpectrumFrame(...) on a buffered window when you need a raw single-frame FFT.
Custom quantization ranges
Both quantized read paths accept an optional StreamQuantizeConfig second argument. The defaults assume a "normal" signal; a stream that is much louder or quieter than that will saturate to all-255 or collapse to 0 once quantized. Widen the ranges so the visible detail survives the 8-bit/16-bit squeeze:
// A hot live input: lift the mel floor and raise the onset/RMS ceilings.
const u8 = analyzer.readFramesU8(analyzer.availableFrames, {
melDbMin: -60, // default -80; raise the floor for a loud stream
melDbMax: 0, // default 0
onsetMax: 80, // default 50; avoid clipping strong transients
rmsMax: 1.5, // default 1
centroidMax: 11025,
});The same StreamQuantizeConfig applies to readFramesI16(...). Omit the argument to keep the defaults. Only the output mapping changes; the internal float analysis is unaffected.
Drawing the frames
import type { StreamAnalyzer } from '@libraz/libsonare';
function renderVisualization(frames: ReturnType<StreamAnalyzer['readFrames']>, nMels: number) {
const { nFrames, mel, chroma, onsetStrength } = frames;
if (!mel || !chroma || !onsetStrength) return; // a feature that is not computed is absent
for (let f = 0; f < nFrames; f++) {
for (let m = 0; m < nMels; m++) {
// mel is unnormalised linear power (a loud frame reaches 1e4 or more), so map it through dB
const db = 10 * Math.log10(mel.data[m * nFrames + f] + 1e-10);
const value = Math.min(1, Math.max(0, (db + 80) / 80)); // -80 dB..0 dB -> 0..1
// Draw pixel at (scrollX + f, nMels - m)
}
for (let c = 0; c < 12; c++) {
const value = chroma.data[c * nFrames + f]; // 12 pitch classes, band-major
}
if (onsetStrength[f] > 1.5) triggerBeatEffect(); // tune the threshold for your audio
}
}readFramesU8 already maps mel dB from -80 to 0 onto 0-255, so with it you can skip the conversion above.
Progressive estimates: BPM, key, chord, and pattern
stats() returns a StreamStats whose estimate field is a StreamProgressiveEstimate — the analyzer's running best guess at the music, refined as more audio arrives. Check estimate.updated before reading: it is true on the periodic frames where the key or BPM estimate is recomputed (not only on frames where the recomputed value actually differs from before), so you can skip the frames where nothing was recomputed at all.
const { estimate } = analyzer.stats();
if (estimate.updated) {
// Tempo and key (absent until estimated)
estimate.bpm; estimate.bpmConfidence;
estimate.key; // Key { root, mode, confidence, name, shortName }, e.g. name "A minor"
// The chord playing right now (absent until the analyzer has an estimate)
estimate.chord; // StreamChordChange { root, quality, name, startSec, confidence }
// The progression so far
estimate.chordProgression; // StreamChordChange[]
estimate.barChordProgression; // StreamBarChord[] beat-synchronized, one per bar
// Pattern detection (e.g. a I–V–vi–IV loop)
estimate.detectedPatternName; // best-matching known progression
estimate.detectedPatternScore;
estimate.allPatternScores; // StreamPatternScore[] { name, score }
estimate.votedPattern; // StreamBarChord[] the locked, repeating pattern
estimate.patternLength; // bars in that pattern
estimate.currentBar; // estimate.barDurationSec -> bar position/length
// How much the estimate is built on
estimate.bpmCandidateCount; // tempo candidates the latest BPM estimate chose from
estimate.accumulatedSec; // audio folded into the estimate so far
estimate.usedFrames;
}The BPM estimate becomes available after about 10 seconds (bpmUpdateIntervalSec) and the key after about 5 seconds (keyUpdateIntervalSec). With no pitched content yet (silence), estimate.key and estimate.chord are absent, as are bpm and currentBar. The key estimate is computed from a 186 ms chroma window, so it trails the frame outputs, and nFft is rescaled on a stream below 44100 Hz; see Usage, AudioWorklet integration, and timing.
There are two chord progressions because they answer different questions:
| Field | Meaning |
|---|---|
chordProgression | Raw detected chord changes as they arrive. |
barChordProgression | Chords snapped to bar boundaries, which is easier to read as a chart. |
Pattern detection then votes across bars to recognize a repeating progression (votedPattern / detectedPatternName). That is what makes the display settle into a song-level pattern instead of flickering per frame.
Help pattern lock in with the expected duration
Pattern voting needs enough bars to be confident. If you know the clip length up front, call analyzer.setExpectedDuration(seconds) so timing and the pattern lock are scaled correctly; otherwise the estimate keeps refining as audio streams in. For non-standard tuning, analyzer.setReferenceHz(referenceHz) (the referenceHz config key at construction) shifts the key/chord reference off A4 = 440 Hz.
Tempograms
For the time × tempo picture behind a BPM estimate, computed from an onset envelope, see Tempograms from an onset envelope.
AudioWorklet notes
The regular WASM package exposes the RealtimeEngine class. The worklet bridge runs that embind-backed engine inside AudioWorkletGlobalScope through SonareRealtimeEngineNode.create(...). For the engine's own control surface — transport, automation, MIDI clips, and external MIDI — see Realtime Engine, and for mixing on it Mixing on the Realtime Engine.
The bridge helpers live under the package subpath @libraz/libsonare/worklet. Register the processor inside the worklet module, then create the node on the main thread. moduleUrl is the compiled worklet module that calls registerSonareRealtimeEngineWorkletProcessor().
// sonare-engine-worklet.ts
import { registerSonareRealtimeEngineWorkletProcessor } from '@libraz/libsonare/worklet';
registerSonareRealtimeEngineWorkletProcessor();// main.ts
import { init } from '@libraz/libsonare';
import { SonareRealtimeEngineNode } from '@libraz/libsonare/worklet';
await init();
const audioCtx = new AudioContext();
const engineNode = await SonareRealtimeEngineNode.create(audioCtx, {
moduleUrl: '/sonare-engine-worklet.js',
numChannels: 2,
mode: 'auto', // uses SharedArrayBuffer (SAB) when available, postMessage otherwise
});
engineNode.node.connect(audioCtx.destination);
engineNode.play();
engineNode.onTelemetry((telemetry) => console.log(telemetry));
console.log(engineNode.capabilities.mode, engineNode.capabilities.degradedReason);
// In requestAnimationFrame or another UI tick, drain SAB telemetry if used.
engineNode.pollTelemetry();
// Later:
engineNode.destroy();Send PFL/AFL to a separate cue output
PFL/AFL monitoring folds the cue bus into the program output by default; the cueOutput: true option, which gives the node a second, cue-only output, is described under monitor taps.
Mastering preview in the render realm
StreamingMasteringChain is also exported from @libraz/libsonare/worklet, so a live mastering preview can stay in the render realm. Construct and prepare() it from a message handler, never from AudioWorkletProcessor.process(): preparation allocates. A loudness stage needs an offline-measured loudnessStaticGainDb, because integrated LUFS cannot be measured block by block. After the final block, flush until empty and discard the leading latencySamples() samples when alignment matters. The chain is a host-side stage, outside the engine's delay compensation and bypass, so compensate it against other engine outputs yourself.
The SonareEngine facade
For app code that wants a higher-level worklet API, SonareEngine combines two pieces:
| Piece | Role |
|---|---|
| Worklet node | Runs the realtime audio side. |
Main-thread RealtimeEngine | Handles offline and timeline operations. |
Its transport API covers play/stop, seek by seconds or PPQ (musical position in quarter-note units), tempo, and loop updates. Beyond transport, the worklet API mirrors essentially the whole engine to the worklet through control messages — the main thread stays the single source of truth and the audio thread receives synced snapshots. The methods are listed by need, with the ring and command-record constants, in Worklet engine facade.
import { SonareEngine } from '@libraz/libsonare/worklet';
const engine = await SonareEngine.create(audioCtx, {
moduleUrl: '/sonare-engine-worklet.js',
mode: 'auto',
numChannels: 2,
});
engine.setTrackLanes([{ trackId: 1 }]);
engine.setStrip(1, trackStrip);
engine.addClip(1, { channels: [clipL, clipR], startPpq: 0 });
engine.setTempoSegments([{ startPpq: 0, bpm: 120 }]);
engine.transport.setLoop({ startPpq: 0, endPpq: 4, enabled: true });
engine.transport.play();
engine.onMeter((meter) => {
const leftRms = meter.rmsDb[0];
const rightRms = meter.rmsDb[1];
if (leftRms !== undefined && rightRms !== undefined) console.log(leftRms, rightRms);
});
const offline = await engine.renderOffline({ totalFrames: 48000 });
console.log(offline[0].length);
engine.destroy();SonareEngine.create, SonareRealtimeEngineNode.create, the playback node, and SonareStreamAnalyzerNode.create take an optional sampleRate. The worklet always runs at the AudioContext's rate, so a value that differs from audioCtx.sampleRate throws RangeError before any node exists; omit it. The voice-changer, mixer, engine and playback processors all run at the AudioWorkletGlobalScope sample rate, and outside a worklet scope the rate must be given. A quantum larger than the engine's prepared size renders silence.
Offline export (renderOffline, bounceOffline, freezeOffline) and the node-level transport and polling methods are described in Offline render, bounce, and freeze. To analyze a branch of your audio graph without writing a processor, use SonareStreamAnalyzerNode; see Streaming Analyzer in the Browser.
Worklet sync messages
SonareEngine runs the full embind engine inside the worklet. If your host worklet entry filters message names before forwarding, allowlist every sync*, captureRequest, and transportRequest message — otherwise lane/strip/MIDI sync messages are silently dropped.
The main package entry (@libraz/libsonare) also ships two main-thread browser integration helpers: bindMicrophoneInput(...) wires getUserMedia into an AudioWorklet engine node (see Recording and Takes), and bindWebMidi(...) bridges Web MIDI input to the engine (see MIDI Input). If microphone setup fails, bindMicrophoneInput stops the tracks it acquired.
The package also ships a ready-made voice-changer processor; registering it and driving it with setConfig messages is covered in Realtime Voice Changer.
Display waveform peaks
Drawing a clip at any zoom reduces it to min/max peaks per screen column with waveformPeaks(...) and waveformPeakPyramid(...); see Drawing the recorded waveform.
Related
- Streaming Analyzer in the Browser —
SonareStreamAnalyzerNodeand a custom analyzer worklet - Paged Clip Audio Streaming — page providers, lookahead, and OPFS-backed clips
- JavaScript/TypeScript Streaming and Realtime API —
StreamAnalyzertypes, the worklet engine facade, and the other block-by-block processors - Realtime Engine — transport, automation, MIDI clips, and external MIDI routing for the engine this page's bridge and clip streaming feed
- Mixing on the Realtime Engine — lanes, buses, strips, PFL/AFL taps, group routing, sidechains, and surround buses
- Mixing Engine — strips, buses, sends, and metering for multi-track realtime
- JavaScript API · Python API — the batch feature transforms behind these estimates
- DSP Implementation Notes — how onset, chroma, and tempo features are built