JavaScript/TypeScript Streaming and Realtime API
Block-by-block processors for the libsonare JavaScript/TypeScript package: StreamingEqualizer, StreamingRetune, RealtimeVoiceChanger with its realtimeVoiceChangerRender(...) convenience call, StreamingMasteringChain, the incremental StreamAnalyzer, the worklet engine facade, and the inverse reconstruction helpers; see Mastering API for the offline chain, presets, and one-shot processors.
StreamingEqualizer
StreamingEqualizer is the block-by-block EQ object used for realtime-safe processing: up to 24 bands, zero-latency/natural/linear phase modes, dynamic EQ, mid/side processing, external sidechain input, spectrum snapshots, and offline reference matching. In the WASM package, call init() first and destroy() when done.
import { init, StreamingEqualizer } from '@libraz/libsonare';
await init();
const eq = new StreamingEqualizer({ sampleRate: 48000, maxBlockSize: 512 });
try {
eq.setBand(0, {
type: 'highShelf',
frequencyHz: 8000,
gainDb: 4,
q: 0.7,
enabled: true,
});
eq.setPhaseMode('zero'); // 'zero' (zero latency), 'natural' or 'linear'
eq.setAutoGain({ enabled: true });
const { left, right } = eq.processStereo(leftBlock, rightBlock);
console.log(eq.spectrum(), eq.latencySamples, left, right);
} finally {
eq.destroy();
}For a first-order low or high shelf, set the band's slopeDbOct to 6. Its frequencyHz is then where the shelf reaches half its gain change in dB, and q has no effect. Leaving slopeDbOct unset uses the regular shelf design shown above.
CLI equivalents for file-based EQ and filtering. eq and filter exist in both the Python and the C++ CLI.
sonare eq track.wav --type 2 --frequency-hz 8000 --gain-db 4 --q 0.7 -o eq.wav
sonare filter track.wav --type high-pass --cutoff-hz 80 -o filtered.waveq --type takes the band type ordinal in the order of EqBandType, so 9 is the all-pass band on both CLIs. Linear-phase mode refuses an all-pass band by name.
nonFiniteDiscardCount counts the processed blocks in which a non-finite sample reached the EQ and its recursive filter state was discarded; see Non-finite input.
StreamingRetune
StreamingRetune is the block-by-block mono pitch retune object. It maintains grain and delay state across calls. Before the first nonempty block, call prepare(sampleRate, maxBlockSize) with integer values in [8000, 384000] Hz and [1, 1048576] samples. An out-of-domain value raises RangeError and preserves the previous preparation. An empty block returns an empty array even before preparation. Call destroy() when done.
import { init, StreamingRetune } from '@libraz/libsonare';
await init();
const retune = new StreamingRetune({ pitchSemitones: 3, mix: 1 });
retune.prepare(48000, 512);
try {
const out = retune.processMono(inputBlock);
retune.setConfig({ pitchSemitones: -2, mix: 0.75 });
console.log(out, retune.config(), retune.grainSizeSamples);
} finally {
retune.destroy();
}Closest CLI equivalents for offline files (both the Python and the C++ CLI):
sonare pitch-shift vocal.wav --pitch-semitones 3 -o shifted.wav
sonare voice-change vocal.wav --pitch-semitones 3 --formant-factor 1.0 -o voice.wavRealtimeVoiceChanger
RealtimeVoiceChanger is the preset-based live voice chain (high-pass, gate, retune, formant, EQ, compressor, de-esser, reverb, and limiter stages) that keeps state across audio blocks. Use it for monitoring, AudioWorklet-style processing, or chunked voice rendering where voiceChange(...) is too simple. Factory preset IDs come from realtimeVoiceChangerPresetNames(); preset JSON is fetched with realtimeVoiceChangerPresetJson(...) and checked with realtimeVoiceChangerValidatePresetJson(...) (schema version 4). RealtimeVoiceChangerConfigInput is strict: use one of the twelve VoicePresetId strings or a preset object with either a dsp object or a macros object, never both.
import { init, RealtimeVoiceChanger, realtimeVoiceChangerPresetNames } from '@libraz/libsonare';
await init();
const changer = new RealtimeVoiceChanger({
sampleRate: 48000,
maxBlockSize: 128,
numChannels: 1,
config: 'brightIdol',
});
try {
const out = changer.processMono(inputBlock);
const realtime = changer.createRealtimeMonoBuffer(128); // zero-copy WASM heap view
realtime.input.set(inputBlock.subarray(0, 128));
realtime.process();
console.log(out, realtime.output, changer.latencySamples);
} finally {
changer.destroy();
}The twelve factory presets are neutralMonitor, brightIdol, softWhisper, deepNarrator, robotMascot, darkVillain, hardTune, robotMonotone, choirHarmony, vocoderStrings, megaphone and radioVoice; realtimeVoiceChangerPresetNames() returns the same list at runtime.
| Task | Methods |
|---|---|
| Configure | The constructor, new RealtimeVoiceChanger({ sampleRate, numChannels, maxBlockSize?, config? }), which prepares the changer (create a new one to change the rate, block size or channel count), setConfig(config), config(), configJson() |
| Process, allocating the result | processMono(samples), processPlanar(channels) |
| Process into your own array | processMonoInto(samples, output), processInterleavedInto(input, numChannels, output) |
| Zero-copy | createRealtimeMonoBuffer, createRealtimeInterleavedBuffer, createRealtimePlanarBuffer; fill the view and call its process() |
| State | reset(), latencySamples, nonFiniteDiscardCount, destroy() |
A configuration value that is non-finite or outside its range (through the constructor, setConfig or automation) throws a RangeError naming the field and its range, and the previous configuration stays in effect; nothing is clamped. The zero-copy buffer helpers return changer-owned WASM heap views; reuse them inside a realtime loop and discard after destroy(). The buffers are views onto the WASM heap that re-acquire themselves when the heap grows, so a view from createRealtimeMonoBuffer, createRealtimeInterleavedBuffer or createRealtimePlanarBuffer stays usable. See Realtime Voice Changer for the preset list and the order of the chain stages, and Realtime safety for what a realtime loop may and may not do.
realtimeVoiceChangerRender(request)
realtimeVoiceChangerRender(...) is the offline whole-buffer convenience function around RealtimeVoiceChanger. It internally constructs and prepares a changer, runs the per-block render loop for you, then disposes it — matching the Python realtime_voice_changer_render and Node equivalents — so callers do not manage the stateful object themselves.
function realtimeVoiceChangerRender(request: {
channels: Float32Array[]; // one (mono) or two (stereo) planar channels of equal length
sampleRate: number; // required
config?: RealtimeVoiceChangerConfigInput; // preset id, preset document or flat config; default 'neutralMonitor'
}): Float32Array[] // the processed channels, same layout and length as the inputA missing sampleRate is a TypeError; a channel count other than one or two, channels of unequal length, or an unknown preset id is a RangeError.
Use this when you already have the full buffer. Reach for RealtimeVoiceChanger for manual block-by-block live use, and voiceChange(...) when you only need a one-shot pitch/formant change without the full preset chain.
StreamingMasteringChain
For real-time or memory-constrained use cases, such as processing audio block-by-block from AudioWorklet or a stream, the WASM module exposes StreamingMasteringChain. It accepts a StreamingMasteringChainConfig, which extends MasteringChainConfig with two optional streaming-only fields:
loudnessStaticGainDb— a precomputed static loudness gain in dB (e.g.targetLufs - measuredIntegratedLufs), applied per block so a preset's streaming preview matches its offline render with aloudnessstage enabled.loudnessStaticGainPeakDbtp— the offline-measured source true-peak in dBFS. When set, the static gain is clamped toloudness.ceilingDbtp - loudnessStaticGainPeakDbtpso the streaming limiter does not receive a hotter input than the offline chain.
It otherwise prepares processor state for a fixed block size and applies the chain incrementally.
import { init, StreamingMasteringChain } from '@libraz/libsonare';
await init();
const chain = new StreamingMasteringChain({
sampleRate: 48000,
maxBlockSize: 512,
numChannels: 2,
eq: { tilt: { tiltDb: 0.5 } },
dynamics: { compressor: { thresholdDb: -20 } },
maximizer: { truePeakLimiter: { ceilingDbtp: -1, oversampleFactor: 4 } },
});
// Use the path that matches the configured channel count: processMono() /
// flushMono() with numChannels: 1, processStereo() / flushStereo() with
// numChannels: 2. Mixing them throws a num_channels mismatch.
const { left, right } = chain.processStereo(leftBlock, rightBlock);
chain.setParameter('eq.tilt.tiltDb', 1.0);
console.log(chain.stageNames()); // ['eq.tilt', 'dynamics.compressor', ...]
console.log(chain.latencySamples); // total latency reported by active stages
// After the last input block, drain the chain latency and the finite tails.
let tail: { left: Float32Array; right: Float32Array };
while ((tail = chain.flushStereo()).left.length > 0) {
write(tail.left, tail.right);
}
chain.reset(); // clear processor state, keeping the configuration
chain.destroy(); // release the WASM handle (call when done)setParameter(key, value) updates one realtime-safe parameter on the chain. The write is serialized at a block boundary while the chain keeps its processor instances, audio history, and latency. Keys use their full dotted form, such as eq.tilt.tiltDb; only realtime-safe keys belonging to enabled stages are available. A multiband stage retargets every band live through dynamics.multibandComp.band<i>.<field> (thresholdDb, ratio, attackMs, releaseMs, makeupGainDb). Structural keys, keys from disabled stages, and unknown keys are rejected. Serialize calls to setParameter() with process*(), flush*(), and reset(); parameter changes take effect at the boundary and are not smoothed automatically. An undeclared key raises TypeError with the supplied key and the sorted accepted keys.
flushMono() / flushStereo() emit the delayed audio plus finite processor tails once you have no more input. Call until an empty result comes back. Without the flush, a bounce built from a streaming chain loses its last latencySamples samples and any reverb or limiter tail. The first latencySamples samples of the concatenated stream are the chain's delay and should be dropped for a time-aligned result.
nonFiniteDiscardCount and nonFiniteSubstitutionCount report degraded input; see Non-finite input. Stereo-only stages are skipped when numChannels === 1. Of the chain-config repair stages, only repair.denoise runs on the streaming chain, and only with a causal noise estimator (noiseEstimator is the mcra, imcra or spp name; an ordinal is a TypeError). It defaults to spp, so repair.denoise.enabled alone prepares; the quantile estimator ranks the whole signal's frames, so the constructor refuses it by name with a SonareError of code NotSupported. repair.declick, repair.dereverb, repair.declip, repair.decrackle and repair.dehum throw the same NotSupported error if enabled here — run them through masterAudio*, the one-shot masteringRepair* helpers, or as realtime inserts where the stage has one. The loudness stage also throws (a RangeError) unless you supply loudnessStaticGainDb (optionally with loudnessStaticGainPeakDbtp), since the streaming chain cannot measure whole-signal integrated LUFS. Call reset() between independent songs and destroy() to free the handle.
Streaming API
The Streaming API enables real-time audio analysis for visualizations and live monitoring. Unlike batch analysis, streaming processes audio chunk by chunk with minimal latency. Background: Streaming analysis.
When to Use
- Batch API: Pre-recorded files, all-in-one analysis (BPM, key, chords, sections)
- Streaming API: Live audio, visualizations, real-time feedback
This section is the StreamAnalyzer type/class reference. For the runnable recipe, the AudioWorklet bridge, output-format details, and the progressive-estimate walkthrough, see Realtime and Streaming.
StreamConfig
Configuration options for StreamAnalyzer.
interface StreamConfig {
sampleRate: number; // required, in Hz
nFft?: number; // default: 2048, in samples at 44100 Hz
hopLength?: number; // default: 512
nMels?: number; // default: 128
fminHz?: number; // default: 0
fmaxHz?: number; // absent = sampleRate / 2; an explicit 0 is refused
referenceHz?: number; // A4 reference, default: 440 (220..880)
computeMel?: boolean; // default: true
computeChroma?: boolean; // default: true
computeOnset?: boolean; // default: true
computeSpectral?: boolean; // default: true
emitEveryNFrames?: number; // default: 1 (no throttling)
maxPendingFrames?: number; // default: 4096; overflow drops newly produced output frames
maxProgressionEntries?: number; // default: 4096; cap for each retained chord/bar progression, overflow drops oldest
keyUpdateIntervalSec?: number; // default: 5
bpmUpdateIntervalSec?: number; // default: 10
window?: WindowType; // 'hann' (default), 'hamming', 'blackman' or 'rectangular'
}Choose a quantized read explicitly with readFramesU8 or readFramesI16; analysis itself always runs in float. See Realtime and Streaming.
nFft is a duration written as samples at 44100 Hz: on a stream at a lower sampleRate the window is rescaled to the analysis rate (never shorter than hopLength), and hopLength stays in input samples. The emitted bin count follows the FFT length the window is zero-padded to, not nFft / 2 + 1.
There is no magnitude output: the StreamAnalyzer read paths do not expose magnitude frames, and a key the config does not declare is a TypeError. Use stft({ db: true }) offline or the spectrum metering helpers for magnitude data.
Omit any StreamConfig field other than sampleRate to take the library default; the defaults are the values in the comments above.
StreamAnalyzer Class
class StreamAnalyzer {
constructor(config: StreamConfig);
// Process an audio chunk. Without startSample the analyzer tracks the
// offset itself; with it, the chunk starts at that cumulative sample count.
// A gap, seek, or switch between the two forms requires reset() first.
process(samples: Float32Array, startSample?: number): void;
// Flush the tail at end of stream: drains the high-rate resampler tail and
// zero-pads the final partial frame. A repeat call is a no-op; process()
// afterwards throws until reset().
finalize(): void;
// Number of frames ready to read
readonly availableFrames: number;
// Read processed frames (full float precision)
readFrames(maxFrames: number): StreamFrames;
// Quantized reads for bandwidth-reduced transfer / visualization
// (optional quantizeConfig widens quantization ranges for unusually loud/quiet streams;
// see Realtime and Streaming → custom quantization ranges)
readFramesU8(maxFrames: number, quantizeConfig?: StreamQuantizeConfig): StreamFramesU8; // Uint8 feature arrays
readFramesI16(maxFrames: number, quantizeConfig?: StreamQuantizeConfig): StreamFramesI16; // Int16 feature arrays
// Reset state for new stream
reset(startSample?: number): void;
// Get statistics and estimates that update as audio arrives
stats(): StreamStats;
// Total frames processed
readonly frameCount: number;
// Current time position (seconds)
readonly currentTimeSec: number;
// The sample rate
readonly sampleRate: number;
// Set expected total duration for pattern lock timing
setExpectedDuration(durationSec: number): void;
// Set normalization gain for loud/compressed audio
setNormalizationGain(gain: number): void;
// Set the A4 reference frequency (default: 440 Hz)
setReferenceHz(referenceHz: number): void;
// Release resources (call when done).
destroy(): void;
}StreamFrames
Structure-of-Arrays format for efficient transfer via postMessage; a feature array is absent when its feature is not computed.
interface StreamFrames {
nFrames: number;
timestampsSec: Float32Array; // [nFrames]
mel?: Matrix2D; // rows = mel bands, cols = frames; absent if computeMel is off
chroma?: Matrix2D; // rows = chroma bins, cols = frames; absent if computeChroma is off
onsetStrength?: Float32Array; // [nFrames], absent if computeOnset is off
rmsEnergy?: Float32Array; // [nFrames]
spectralCentroid?: Float32Array; // [nFrames], absent if computeSpectral is off
spectralFlatness?: Float32Array; // [nFrames], absent if computeSpectral is off
chordRoot?: Int32Array; // [nFrames], absent if computeChroma is off
chordQuality?: Int32Array; // [nFrames], absent if computeChroma is off
chordConfidence?: Float32Array; // [nFrames], absent if computeChroma is off
}StreamChordChange
A detected chord change in the progression.
interface StreamChordChange {
root: PitchClass;
quality: ChordQuality;
name: string; // chord symbol, e.g. "C", "C#m", "N.C."
startSec: number;
confidence: number;
}StreamBarChord
A chord detected at bar boundary (beat-synchronized).
interface StreamBarChord {
barIndex: number;
root: PitchClass;
quality: ChordQuality;
name: string; // chord symbol, spelled as the batch analysis spells it
startSec: number;
confidence: number;
}StreamPatternScore
Match score for a known chord progression pattern.
interface StreamPatternScore {
name: string; // pattern name (e.g., "royalRoad", "pop")
score: number; // match score (0-1)
}StreamStats
interface StreamStats {
totalFrames: number;
totalSamples: number;
durationSec: number;
pendingFrames: number; // unread frames currently buffered
droppedOutputFrames: number; // newly produced frames dropped at the configured cap
droppedChordProgressionEntries: number; // oldest chord-history entries dropped at the configured cap
droppedBarProgressionEntries: number; // oldest bar-history entries dropped at the configured cap
nonFiniteDiscardBlocks: number; // process() calls in which a non-finite sample was replaced
estimate: StreamProgressiveEstimate;
}StreamProgressiveEstimate
BPM, key, and chord estimates that improve over time as more audio is processed.
interface StreamProgressiveEstimate {
// A field is absent until the analyzer has an estimate for it.
// BPM estimation
bpm?: number;
bpmConfidence?: number; // 0-1, increases over time
bpmCandidateCount: number;
// Key estimation
key?: Key; // { root, mode, confidence, name, shortName }
// Chord estimation (current)
chord?: StreamChordChange;
chordProgression: StreamChordChange[]; // detected chord changes
barChordProgression: StreamBarChord[]; // bar-synchronized chords
currentBar?: number; // current bar index
barDurationSec?: number; // bar duration in seconds
// Pattern detection
votedPattern: StreamBarChord[]; // voted chord for each pattern position
patternLength: number; // length of repeating pattern (default: 4 bars)
detectedPatternName?: string; // best matching pattern name (e.g., "royalRoad")
detectedPatternScore?: number; // match score (0-1)
allPatternScores: StreamPatternScore[]; // all known pattern scores
// Statistics
accumulatedSec: number;
usedFrames: number;
updated: boolean; // true if estimate changed this frame
}The key is estimated from the stream's own 186 ms chroma, so it trails the input by up to about a quarter second more than the frame outputs do. Every confidence, including per-frame chordConfidence and each StreamChordChange / StreamBarChord confidence, stays in 0-1. key.name, key.shortName and chord.name spell the estimate the way the batch analysis does, so a UI can show them without mapping the root itself.
Non-finite input
A NaN or infinity in the input does not raise an error in the processors below; each replaces it or discards the state it reached, so the output stays finite while no longer describing the input. These counters are the only report that happened.
| Object | Counter | Counts | Cleared by |
|---|---|---|---|
StreamAnalyzer | stats().nonFiniteDiscardBlocks | process() calls in which a non-finite sample was replaced | reset() |
StreamingEqualizer | nonFiniteDiscardCount | Processed blocks in which a filter's recursive state was discarded | never |
RealtimeVoiceChanger | nonFiniteDiscardCount | Processed blocks in which the chain discarded its own state | never |
StreamingMasteringChain | nonFiniteDiscardCount | Processing calls in which a stage discarded its recursive state | never |
StreamingMasteringChain | nonFiniteSubstitutionCount | Samples a true-peak limiter replaced with a finite value | never |
The unit is a block or call, never a sample or a channel. StreamingMasteringChain is the exception to the rule above: a non-finite sample in its input is rejected with a RangeError before any stage runs.
Usage, AudioWorklet integration, and timing
The runnable StreamAnalyzer recipe — feeding blocks from an AudioWorklet, reading frames, throttling with emitEveryNFrames, and mapping the StreamFrames stream-time timestamps onto AudioContext.currentTime — lives on Realtime and Streaming, with the AudioWorklet handshake and data-flow diagrams.
Releasing WASM objects
StreamAnalyzer, Mixer, StreamingEqualizer, and StreamingMasteringChain are embind handles onto WASM heap memory that the JavaScript garbage collector cannot reclaim — call destroy() when done. Plain functions like analyze() return ordinary JS values and need no cleanup. Releasing twice is a no-op; calling any other method on a released handle throws InvalidState. Node native cleanup differs; see Native Bindings.
Worklet engine facade
The SonareEngine facade methods, the offline render calls and the node-level polling methods are on SonareEngine API.
Inverse reconstruction
Mel and MFCC inversion (melToStft, melToAudio, mfccToMel, mfccToAudio) is on Feature Extraction API.