Node.js Native Analysis, Effects and Utilities
This page lists the analysis, effects, feature-extraction, inverse-reconstruction, librosa-compatible, conversion, metering and scale-quantization functions of the @libraz/libsonare-native package, plus the stateful methods of its project, engine and mixer classes. For usage, errors, the Audio class, releasing handles, mastering and the streaming classes, see Node.js Native API; for the exported TypeScript types, see Node.js Native Types.
Usage Examples
Audio Effects
import { Audio } from '@libraz/libsonare-native';
const audio = Audio.fromFile('music.mp3');
// Harmonic-Percussive Source Separation
const hpssResult = audio.hpss();
const harmonic = audio.harmonic();
const percussive = audio.percussive();
// Time stretch / pitch shift
const stretched = audio.timeStretch({ speedRatio: 1.5 }); // 1.5x speed
const shifted = audio.pitchShift({ pitchSemitones: 2 }); // Up 2 semitones
// Normalize and trim silence
const normalized = audio.normalize({ targetDb: 0 }); // 0 dB
const trimmed = audio.trim({ thresholdDb: -60 });Feature Extraction
See Node.js Native Feature Extraction for the feature-extraction examples.
Unit Conversions
import {
hzToMel, melToHz, hzToMidi, midiToHz,
hzToNote, noteToHz, framesToTime, timeToFrames
} from '@libraz/libsonare-native';
hzToMel(440); // → 6.6 (Slaney mel scale)
melToHz(6.6); // → 440
hzToMidi(440); // → 69
midiToHz(69); // → 440
hzToNote(440); // → "A4"
noteToHz('A4'); // → 440
framesToTime(100, 22050, 512); // → seconds
timeToFrames(2.32, 22050, 512); // → frame index (arguments: value, sampleRate, hopLength)Analysis Functions
Every function takes a request object whose sampleRate is required (there is no default); a mono entry point also accepts (samples, sampleRate, options?). Beat, downbeat and onset times mark the start of the evidence that produced them. Each function refuses a non-finite sample with a RangeError; see the error contract.
| Function | Return Type | Description |
|---|---|---|
detectBpm({ samples, sampleRate, bpmMin?, bpmMax? }) | number or undefined | Tempo in BPM, or undefined when no tempo is found |
detectKey({ samples, sampleRate, ...options }) | KeyDetection | Root (a pitch-class number, C = 0), mode (a name such as 'major' or 'dorian'), confidence, and the tuningCents the chroma was built with. options takes the detectKeyCandidates options; tuningCents (a number in [-50, 50) or 'auto') is measured from the audio unless given, and 0 reads at A440 |
detectBeats({ samples, sampleRate, bpmMin?, bpmMax? }) | Float32Array | Beat timestamps |
detectOnsets({ samples, sampleRate, ...options }) | Float32Array | Onset timestamps. options: nFft, hopLength, threshold, preMax, postMax, preAvg, postAvg, delta, wait, backtrack, backtrackRange |
detectChords({ samples, sampleRate, ...options }) | ChordAnalysisResult | Chord progression with timings, plus the tuningCents used. Frames below threshold are returned as explicit N.C. intervals. options: minDurationSec, smoothingWindowSec, threshold, useTriadsOnly (default true), nFft, hopLength, useBeatSync, useHmm (default true), hmmBeamWidth, useKeyContext with keyRoot / keyMode, detectInversions, chromaMethod ('cqt' default), and tuningCents (a number or 'auto', measured unless given, 0 for A440) |
chordFunctionalAnalysis({ samples, sampleRate, keyRoot, keyMode?, ...options }) | FunctionalChord[] | Detects chords, then returns the timed entries with romanNumeral ('I', 'V7', 'vi') and function ('tonic', 'subdominant', 'dominant', 'chromatic', 'none') added. keyRoot and keyMode take a pitch-class number or name and a mode name, so detectKey's result goes straight back in; options are the detectChords options |
chordFunctions({ chords, key }) | FunctionalChord[] | Labels chords you already have with romanNumeral and function in key, without re-detecting. chords is a detectChords result or its chords; key is { root, mode }, so detectKey's result goes in as it is |
detectDownbeats({ samples, sampleRate }) | Float32Array | Downbeat (bar-start) timestamps |
detectKeyCandidates({ samples, sampleRate, ...options }) | KeyCandidate[] | Ranked key candidates with correlation scores. options: nFft, hopLength, useHpss, loudnessWeighted, chromaHighPassHz, tuningCents (a number or 'auto'; measured unless given, 0 for A440), modes ('majorMinor', 'modal', 'all', or a list of names), profile (pins the key-profile family and outranks genreHint; omit it to let genreHint, or the chroma under the default 'auto' hint, choose), genreHint |
analyze({ samples, sampleRate, ...options }) | AnalysisResult | All-in-one analysis in one call: BPM and ranked BPM hypotheses, key, time signature and ranked time-signature candidates, beats, chords (including romanNumeral relative to the detected key), sections, timbre, dynamics, rhythm, melody, form, and the tuningCents used. The dedicated detect*/analyze* functions below remain available for targeted or parameterized analysis |
estimateMeter({ observations, ...options }) | MeterEstimate | Score beat-level observations without audio or re-running analysis. Request-only — takes EstimateMeterRequest |
analyzeBpm({ samples, sampleRate, ...options }) | BpmAnalysisResult | Tempo with confidence and alternate candidates (candidates[0] is the chosen tempo, the rest follow by vote share). options: bpmMin, bpmMax, startBpm, nFft, hopLength, maxCandidates |
analyzeRhythm({ samples, sampleRate, ...options }) | RhythmResult | Time signature, groove, syncopation. options: bpmMin, bpmMax, startBpm, nFft, hopLength |
analyzeDynamics({ samples, sampleRate, ...options }) | DynamicsResult | Dynamic range, loudness range, crest factor. dynamicRangeDb and crestFactor are absent when not measured; guard before use or formatting. options: windowSec, hopLength, compressionThresholdDb |
analyzeTimbre({ samples, sampleRate, ...options }) | TimbreResult | Brightness, warmth, density, roughness, complexity, plus per-window timbreOverTime. options: nFft, hopLength, nMels, nMfcc, windowSec |
analyzeSections({ samples, sampleRate, ...options }) | SectionAnalysis | Structural sections (intro/verse/chorus…) with timings, as { sections, form }. options: nFft, hopLength, minSectionSec, threshold. Use each section's startSec / endSec for placement |
detectBoundaries({ samples, sampleRate, ...options }) | BoundaryResult | Structural transitions plus the novelty curve they were picked from, and the grid both live on. options: nFft, hopLength, kernelSize, threshold, absoluteThreshold, nMfcc, nChroma, peakDistanceSec, referenceWindowSec (seconds, default 60; the span the relative threshold is measured over, 0 disables it), useMfcc, useChroma. Reach for it when you want to apply your own threshold rather than take analyzeSections' labeled spans |
analyzeMelody({ samples, sampleRate, ...options }) | MelodyResult | Lead-melody contour (F0 per frame). options: f0MinHz, f0MaxHz, frameLength, hopLength, threshold, usePyin, center |
detectAcoustic({ samples, sampleRate, ...options }) | AcousticResult | Room acoustics from a recording (RT60 — the time reverberation takes to decay 60 dB — and related measures). options: nOctaveBands, nThirdOctaveSubbands, minDecayDb, noiseFloorMarginDb |
analyzeImpulseResponse({ samples, sampleRate, nOctaveBands?, minDecayDb? }) | AcousticResult | Room acoustics from a measured impulse response; minDecayDb controls the decay-fit threshold (default 30) |
estimateRoom({ samples, sampleRate, ...options }) | RoomEstimateResult | Equivalent-room estimate: volume, lengthM / widthM / heightM, drrDb (direct-to-reverberant ratio), bandAbsorption, rt60Bands, confidence. options.mode is 'auto' (default), 'blind' or 'impulseResponse'; a number is a TypeError and an unknown name a RangeError |
synthesizeRir({ sampleRate, ...options }) | RirResult | Mono RIR (room impulse response) from shoebox geometry, returned as { rir, sampleRate, diagnostics }. materialPreset takes a name ('none', 'concrete', 'wood', 'curtain', 'carpet', 'glass'); a number is a TypeError. A refused geometry is a RangeError |
roomGeometryFromEstimate({ estimate, source?, listener? }) | RoomGeometry | Turns an estimateRoom result into synthesizeRir input. Source and listener are placed in the estimated room (override with source / listener), and the mean of the bands becomes the scalar absorption. Throws when the estimate has no measurable dimensions |
roomMorph({ samples, sampleRate, ...options }) | RoomMorphResult | Offline creative morph toward a target room; read morphed samples from .audio, with .sampleRate and .diagnostics alongside them |
roomMorphStereo({ left, right, sampleRate, receiverSpacingM?, ...options }) | RoomMorphStereoResult | Stereo roomMorph. The target room is heard at two receivers receiverSpacingM apart (in (0, 4] m, default 0.5 m), so each channel gets its own response; read .left, .right, .sampleRate and .diagnostics |
lufs({ samples, sampleRate }) | LufsResult | Integrated, final momentary/short-term windows, their EBU R128 maxima, and loudness range (loudnessRangeLu) |
lufsMultichannel({ channels, sampleRate }) | LufsResult | Channel-weighted multichannel loudness from planar channels |
lufsSeriesMultichannel({ channels, sampleRate }) | LufsSeriesResult | Momentary and short-term loudness series of a multichannel signal |
ebur128LoudnessRangeLu({ samples, sampleRate }) | number | Standards-compliant EBU R128 loudness range (LRA) in LU |
momentaryLufs({ samples, sampleRate }) | Float32Array | Momentary loudness (400 ms) per step |
shortTermLufs({ samples, sampleRate }) | Float32Array | Short-term loudness (3 s) per step |
version() | string | Library version |
voiceChangerAbiVersion() | number | ABI version of the realtime voice-changer POD config; separate from preset JSON schemaVersion |
voiceCharacterPresetId(ordinal) | VoicePresetId | Canonical voice-character preset ID of an ordinal; an out-of-range ordinal throws |
realtimeVoiceChangerPresetConfig(preset) | RealtimeVoiceChangerConfig | Resolved flat config for a built-in voice preset, without JSON parsing. Throws on an unknown preset name or out-of-range ordinal |
Whether the loaded addon can decode via FFmpeg is capabilities().features.ffmpeg. Common helpers are also available as Audio instance methods, as noted in the Audio section; some detailed helpers, such as analyzeSections(...), analyzeMelody(...), cqt(...) and vqt(...), are standalone functions only, so pass them audio.data and audio.sampleRate. The WASM package uses the same camelCase names; see JavaScript API for the browser signatures.
analyze() options
analyze(...) takes the options as fields of the request object, or as an options object third argument. It covers the whole pipeline in one place:
| Option | Default | Description |
|---|---|---|
nFft / hopLength | 2048 / 512 | STFT resolution shared across the pipeline. nFft is samples at 22050 Hz, rescaled to the input rate; hopLength is samples of the input |
bpmMin / bpmMax / startBpm | 60 / 200 / 120 | Tempo search range and prior |
useTriadsOnly | true | Restrict the chord search to triads |
useHpss | false | Apply harmonic-percussive separation before the chord chroma |
chromaHighPassHz | 80 | Chroma high-pass cutoff in Hz (0 disables) |
useBassWeighted | true | Bass-weighted chroma combination |
chromaHopMultiplier | 4 | Chroma hop multiplier; larger is faster |
useChordHmm / useChordKeyContext / chordHmmBeamWidth / detectChordInversions | true / false / 24 / false | Chord post-processing: HMM smoothing, key-biased transitions, the HMM beam width, and slash-chord bass estimation |
adaptiveTempo | false | Track a locally updated tempo prior through beat tracking |
tempoUpdateIntervalBeats | 8 | Local tempo context length in beats; read only when adaptiveTempo is set |
computeTempoCurve | false | Decode a per-beat local tempo curve into beatLocalBpm |
meterCandidateNumerators | [3, 4, 6] | Meter numerators the estimator scores. At most 16 entries, each in [2, 32]; an empty list is rejected rather than restoring the default, and widening the set does not force a wider meter |
meterDenominator | 4 | Beat unit reported for the detected meter, a power of two in [1, 32]. The estimator still reports 8 on its own when it resolves a compound meter |
tuningCents | 'auto' | Recording tuning offset in cents; must be in [-50, 50), or 'auto' (the default) to measure it from the audio; 0 reads at A440. It shifts the chroma used for key, chords, and sections, and the value used is the result's tuningCents. referenceHzToTuning(...) converts a reference pitch to this unit |
onProgress / cancel | — | A (progress, stage) callback, and a callback that returns true to stop the run |
useTriadsOnly points the other way here
In the unified analyze() path useTriadsOnly is true, while the standalone detectChords(...) defaults it to false. So analyze() searches triads alone — and reports no sevenths or extensions — until the caller passes useTriadsOnly: false.
computeTempoCurve is off because the curve is an extra output rather than a better analysis: nothing else in the result changes, so a caller who never reads it would pay a decode over the beat grid for nothing. The curve also describes the beat grid it was decoded from, and beat tracking holds a fixed tempo prior unless adaptiveTempo is set as well — measuring a tempo that actually moves needs both options.
Progress is the onProgress option of analyze(...): a (progress, stage) callback, with cancel as a separate callback that returns true to request cancellation. The async variant below takes neither.
estimateMeter(...)
estimateMeter(...) scores a caller-supplied BeatObservations record. It reads beat-level observations, so evidence from an existing analysis can be re-scored without running the pipeline again. For the underlying concept, see Meter and grouping.
const result = analyze({ samples, sampleRate });
const meter = estimateMeter({
observations: result.beatObservations,
candidateNumerators: [3, 4, 5, 6, 7],
});
console.log(meter.searched, meter.timeSignature.numerator, meter.grouping);
console.log(meter.unobservedBeats); // masked beats excluded from scoring| Field | Default | Description |
|---|---|---|
observations | — | BeatObservations with required accent. An empty optional stream indicates unmeasured evidence. |
candidateNumerators | [3, 4, 6] | Numerators to score; at most 16 entries, each in [2, 32]; an empty list is a RangeError |
denominator | 4 | Beat unit reported for the detected meter, as requested: a six accented 3+3 comes back with this denominator and grouping [3, 3] |
compoundSubdivisionThreshold | 0.5 | Mean measured subdivision accent relative to mean beat accent at which a six or three is read as compound |
downbeatWeight / measureWeight / subdivisionWeight | 1 / 0.5 / 0.15 | Scoring weights for the first beat of each measure, measure-to-measure accent agreement, and the subdivision pattern |
Pass AnalysisResult.beatObservations as observations. The accent stream is the maximum 5 ms RMS near each beat's strongest attack. Optional lowFrequencyEnergy enables masked-beat scoring and subdivisionAccent carries one midpoint value per beat interval. unobservedBeats lists masked beats in ascending zero-based order, or is empty when per-beat energy is absent.
Two properties decide whether the answer means anything:
- The default candidate set is
{3, 4, 6}. An odd meter is reported only if its numerator was asked for, so a seven needs it listed explicitly. searchedisfalsewhen the beat series was under eight beats. Every other field then carries a fixed fallback rather than a result — includingtimeSignature.confidence, which reads0, so an unchecked read degrades toward "no idea" rather than toward a middling detection. Readsearchedbefore treating a short span's answer as a detection.
grouping reports how the bar divides into accent groups, so a seven comes back as a split such as [2, 2, 3] rather than as a bare seven, and it always sums to the numerator. A single entry means no internal division was resolved. candidateScores is standardized and signed, listed in the order the request gave the numerators: zero is the level a numerator reaches on beats carrying no meter, so only the ordering and the gaps between entries carry meaning, and a score grows with the square root of how many beats were scored. candidates is ordered by descending support instead, so match the two on numerator rather than by index. confidence also changes meaning between its two homes: on timeSignature it is derived from the margin over the runner-up, on a candidates entry it is that candidate's share of the summed support (the entries sum to one), so the two must not share a threshold.
Asynchronous variants (Node only)
The Node addon also exposes Promise-returning variants. They run the DSP pipeline on a libuv worker thread, so the JS event loop is not blocked.
These functions resolve with the same shape as their synchronous counterparts and are Node-native-only. Browser code can instead use OfflineWorkerClient from @libraz/libsonare/worker; it provides task-based analysis and mastering in a Web Worker rather than these identically named functions.
Progress callbacks are not available on the async path. If you need progress updates, use the synchronous call with onProgress. If you only need concurrency, run several async calls in parallel.
| Function | Return Type | Description |
|---|---|---|
analyzeAsync({ samples, sampleRate, ...options }) | Promise<AnalysisResult> | Async variant of analyze(...) |
masterAudioAsync({ samples, sampleRate, preset?, overrides? }) | Promise<MasteringChainResult> | Async variant of masterAudio(...) |
masterAudioStereoAsync({ left, right, sampleRate, preset?, overrides? }) | Promise<MasteringChainStereoResult> | Async variant of masterAudioStereo(...) |
Effects Functions
| Function | Return Type | Description |
|---|---|---|
hpss({ samples, sampleRate, kernelHarmonic?, kernelPercussive?, nFft?, hopLength?, hardMask?, withResidual? }) | HpssResult | Harmonic-Percussive Source Separation; nFft=2048, hopLength=512, hardMask=false by default. With withResidual: true the result also carries residual, the signal neither component claims |
harmonic({ samples, sampleRate }) | Float32Array | Extract harmonic component |
percussive({ samples, sampleRate }) | Float32Array | Extract percussive component |
timeStretch({ samples, sampleRate, speedRatio, nFft?, hopLength? }) | Float32Array | Time-stretch without pitch change; defaults to nFft=2048, hopLength=512 |
phaseVocoder({ samples, sampleRate, speedRatio, nFft?, hopLength? }) | Float32Array | Direct phase-vocoder time scaling |
pitchShift({ samples, sampleRate, pitchSemitones, nFft?, hopLength? }) | Float32Array | Pitch-shift without tempo change; defaults to nFft=2048, hopLength=512 |
remix({ samples, sampleRate, intervals, alignZeros? }) | Float32Array | Reorder or concatenate sample intervals |
remixAlignedIntervals({ samples, sampleRate, intervals, alignZeros? }) | Int32Array | The cut points remix would use, without cutting: one clamped (start, end) pair per input interval, flattened. alignZeros defaults to true here |
normalize({ samples, sampleRate, targetDb?, mode? }) | Float32Array | Normalize to target peak or RMS dB (mode: 'peak' (default) or 'rms'; targetDb defaults to 0 for peak and -20 for rms) |
normalizeStereo({ left, right, sampleRate, targetDb?, mode? }) | NormalizeStereoResult | Normalize a channel pair on a level measured across both channels. Request-only |
trim({ samples, sampleRate, thresholdDb?, frameLength?, hopLength? }) | Float32Array | Trim silence (defaults: -60.0 dB, frameLength=2048, hopLength=512) |
resample({ samples, sampleRate, targetSampleRate }) | Float32Array | Resample to target sample rate |
pitchCorrectToMidi({ samples, sampleRate, currentMidi, targetMidi }) | Float32Array | Retune a held note from one MIDI pitch to another |
pitchCorrectTimevarying({ samples, sampleRate, f0Hz, hopLength?, targetMode?, targetMidi?, scaleRoot?, scaleModeMask?, scaleReferenceMidi?, retuneAmount?, maxCorrectionSemitones?, retuneSpeedMs?, vibratoThresholdCents?, voiced?, voicedProb? }) | Float32Array | Retune a tracked pitch contour frame by frame: targetMode 'midi' (the default) snaps it to the fixed note targetMidi, 'scale' to the scale scaleRoot / scaleModeMask. voiced takes the VoicedFlags union |
autoTune({ samples, sampleRate, key?, retuneAmount?, retuneSpeedMs?, vibratoThresholdCents?, maxCorrectionSemitones?, scaleReferenceMidi? }) | AutoTuneResult | Tune a whole recording to a key: key is 'detect' (default) or { root, mode }. Returns { samples, key }. See Editing DSP |
noteStretch({ samples, sampleRate, onsetSample? | onsetSec?, offsetSample? | offsetSec?, stretchRatio }) | Float32Array | Time-stretch a single note span in place; give a position in samples or in seconds, not both |
noteMove({ samples, sampleRate, onsetSample? | onsetSec?, offsetSample? | offsetSec?, targetOnsetSample? | targetOnsetSec? }) | Float32Array | Move a note span to another onset; exactly one target field is required |
voiceChange({ samples, sampleRate, pitchSemitones?, formantFactor?, formantMode? }) | Float32Array | Pitch + formant shift for voice transformation; formantMode is 'relative' (default) or 'absolute', which keeps formants at fixed frequencies |
trim(...) is the simple threshold edit helper. trimSilence(...) below is the librosa-compatible frame/RMS helper that returns the original sample range.
hpss(...) defaults its median-filter kernels to kernelHarmonic=31 and kernelPercussive=31.
Cutting a stereo take with remix
Zero-crossing snapping is a per-signal decision, so calling remix(...) channel by channel snaps each channel to a different frame and drifts a stereo take apart. Resolve one cut set from one channel with remixAlignedIntervals(...) and apply that same set to every channel. The two entry points point opposite ways by default: remix has alignZeros false, remixAlignedIntervals has it true.
Two guards stop a slice from vanishing under snapping. A signal with no sign change at all — silence, a DC offset, any constant — is not snapped, and a slice that had content but collapses to empty after snapping keeps its unsnapped boundaries.
Normalizing a channel pair
normalizeStereo({ left, right, sampleRate, targetDb?, mode? }) applies one gain to both channels and returns it as appliedGainDb. An all-silent pair raises RangeError. In peak mode the louder channel reaches the target. In RMS mode the target is the root mean square of all samples across both channels. Floating-point output is not clipped.
normalize and normalizeStereo default targetDb to 0 in peak mode and -20 in RMS mode.
VoicedFlags is Int32Array | Uint8Array | Float32Array | readonly number[] | readonly boolean[], so the boolean[] that PitchResult.voicedFlag hands back goes straight into pitch correction with no conversion step:
const pitch = pitchPyin({ samples, sampleRate });
const tuned = pitchCorrectTimevarying({
samples,
sampleRate,
f0Hz: pitch.f0,
targetMidi: 69,
hopLength: 512,
voiced: pitch.voicedFlag, // boolean[] accepted as-is
});voicedProb derives the voicing decision only when voiced is omitted — a frame at or above 0.5 counts as voiced. When voiced is supplied, voicedProb is ignored entirely; in particular it does not scale the per-frame correction amount, so passing both is identical to passing voiced alone. The same holds for voicedProb on pitchCorrectTimevarying(...).
Correction strength is not weighted by voicedProb
Code that assumes the correction is scaled by voicedProb gets stronger correction in the low register than it expects. pYIN's voiced probability is a frequency-dependent observation mass that rises with the fundamental rather than tracking confidence, so as a weight it would under-correct low registers.
voiced and voicedProb must each be the same length as f0Hz. A mismatch throws a RangeError ('voiced must have the same length as f0Hz'), not a SonareError, so isSonareError does not catch it.
Feature Extraction Functions
The feature-extraction functions are listed on Node.js Native Feature Extraction.
Transcription, Annotation and Synth Descriptors
| Function | Return Type | Description |
|---|---|---|
transcribe({ samples, sampleRate, ...options }) | TranscribeResult | Mono audio to MIDI note events on a constant-tempo grid, returned as { events, noteCount, tempoBpm, tuningCents } and ready for Project.setMidiEvents. Beyond the tempo and note-length settings, the request takes maxPolyphony, minFramePeakRatio, minRidgePeakRatio, reattackRatio, minNoteDivision and referenceHz (a number or 'auto'). See Audio to MIDI |
alignTakeToReference({ reference, take, sampleRate, takeSampleRate?, hopLength?, binsPerOctave? }) | AlignTakeToReferenceResult | Warp anchors that map a take onto the reference timeline. takeSampleRate defaults to sampleRate |
chordSymbolFromAnalysis(chord) | ChordSymbolFields | Converts a detectChords or analyze chord into the fields of a chord annotation for Project.annotateChords. See Project MIDI |
keyModeFromAnalysis(mode) | ProjectKeyMode | Converts a key mode name ('minor') into the mode of a key annotation for Project.annotateKeys |
synthEngineParamInfo(engineMode) | SynthParamInfo[] | Range, default and unit of every numeric parameter of a synth engine mode. See Built-in Synthesizer |
synthPatchParamInfo() | SynthParamInfo[] | The same descriptors for the numeric SynthPatch fields; a patch field outside its range, or non-finite, is refused by name with a RangeError. lfoShape is an enum field, listed by synthEnumTables() rather than here |
masteringInsertParamInfo({ insert, sampleRate? }) | MasteringInsertParamInfo[] | Parameter descriptors of one mastering insert processor; sampleRate resolves the Nyquist-relative bounds at that host rate |
Inverse Reconstruction Functions
Inverse reconstruction and the librosa-compatible helpers are listed on Node.js Native Feature Extraction.
Conversion Functions
| Function | Description |
|---|---|
hzToMel(hz) | Hertz → Mel (Slaney scale, as librosa uses by default) |
melToHz(mel) | Mel (Slaney scale) → Hertz |
hzToMidi(hz) | Hertz → MIDI note number |
midiToHz(midi) | MIDI note number → Hertz |
hzToNote(hz) | Hertz → note name (e.g., "A4"); a frequency that is not finite and positive throws RangeError |
noteToHz(note) | Note name → Hertz; a name that does not parse, or an octave outside -1 to 9, throws RangeError |
framesToTime(frames, sampleRate?, hopLength?) | Frame index → seconds (sampleRate default 22050, hopLength default 512) |
timeToFrames(timeSec, sampleRate?, hopLength?) | Seconds → frame index (sampleRate default 22050, hopLength default 512) |
framesToSamples(frames, hopLength?, nFft?) | Frame index → sample index (librosa.frames_to_samples) |
samplesToFrames(samples, hopLength?, nFft?) | Sample index → frame index (librosa.samples_to_frames) |
powerToDb({ values, ref?, amin?, topDb? }) | Power → dB (librosa.power_to_db) |
amplitudeToDb({ values, ref?, amin?, topDb? }) | Amplitude → dB (librosa.amplitude_to_db) |
dbToPower({ values, ref? }) | dB → power |
dbToAmplitude({ values, ref? }) | dB → amplitude |
Metering Functions
Standalone level, dynamics, and stereo-image meters. Each takes a request object (samples and sampleRate, or left, right and sampleRate for the stereo meters); the mono meters also accept (samples, sampleRate, options?). The stereo meters require left and right to be equal length, and every meter refuses a non-finite sample with a RangeError naming the index.
| Function | Return Type | Description |
|---|---|---|
meteringPeakDb({ samples, sampleRate }) | number | Sample peak (dBFS) |
meteringRmsDb({ samples, sampleRate }) | number | RMS level (dBFS) |
meteringCrestFactorDb({ samples, sampleRate }) | number or undefined | Crest factor, peak − RMS (dB). undefined for silence |
meteringCrestFactorDbStereo({ left, right, sampleRate }) | number or undefined | Crest factor across both channels (dB). Request-only; undefined when both channels are silent |
meteringDcOffset({ samples, sampleRate }) | number | Mean (DC) offset, linear amplitude |
meteringTruePeakDbtp({ samples, sampleRate, oversampleFactor? }) | number | Inter-sample peak, ISP — the highest level the waveform reaches between samples, also called true peak (dBTP); oversampleFactor is a power of two in 1..16 (default 4) |
meteringDetectClipping({ samples, sampleRate, thresholdDb?, minRegionSamples? }) | ClippingReport | Clipped-sample runs; thresholdDb is the clip level in dBFS (at most 0; default about −0.0087, which is 0.999 linear) and minRegionSamples defaults to 1 |
meteringDynamicRange({ samples, sampleRate, windowSec?, hopSec?, lowPercentile?, highPercentile? }) | DynamicRangeReport | Sliding-window dynamic range (omit for defaults: window 3 s, hop 1 s, low 0.10, high 0.95) |
meteringStereoCorrelation({ left, right, sampleRate }) | number or undefined | Uncentered correlation (cosine similarity), −1..1; undefined when either channel has zero energy |
meteringStereoWidth({ left, right, sampleRate }) | number or undefined | Side-to-mid RMS amplitude ratio. Infinity when only mid is silent; undefined when mid and side are silent |
meteringVectorscope({ left, right, sampleRate }) | VectorscopeReport | Per-sample mid/side point series |
meteringPhaseScope({ left, right, sampleRate }) | PhaseScopeReport | Phase-scope point series plus summary stats |
meteringSpectrum({ samples, sampleRate, nFft?, applyOctaveSmoothing?, octaveFraction?, dbRef?, dbAmin? }) | SpectrumReport | Welch-averaged magnitude/power/dB spectrum over the whole signal (50%-overlapping Hann frames, averaged) |
meteringSpectrumFrame({ samples, sampleRate, startSample?, ...spectrumOptions }) | SpectrumReport | True single-frame magnitude/power/dB spectrum (one Hann-windowed FFT), not time-averaged like meteringSpectrum; startSample selects where the analysis frame starts |
meteringSilenceRatio({ samples, sampleRate, thresholdDb?, frameLength?, hopLength? }) | number | Fraction of analysis frames whose RMS is below thresholdDb (defaults: -45 dBFS, frameLength=1024, hopLength=256) |
waveformPeaks({ channels, samplesPerBucket? }) | WaveformPeaksReport | Per-channel min/max waveform buckets from planar channels; samplesPerBucket defaults to 512 |
waveformPeakPyramid({ channels, samplesPerBucketLevels? }) | WaveformPeaksReport[] | Waveform peak buckets at several zoom levels; samplesPerBucketLevels defaults to [512, 1024, 2048, 4096] |
Reach for meteringCrestFactorDbStereo(...) whenever the two channels may be out of phase. An inverted pair cancels in the 0.5 * (left + right) downmix meteringCrestFactorDb(...) would need, so the single-channel path sees silence: on a fully inverted pair the stereo meter reads the signal's own crest factor (3.01 dB for a sine) while the downmix is silent and has no crest factor to measure.
Scale Quantization
12-TET (twelve-tone equal temperament) scale helpers for building pitch-correction targets. modeMask is a 12-bit mask where bit i enables the i-th pitch class relative to root (PitchClass, C = 0); natural major is 0b101010110101. scaleReferenceMidi is the tuning anchor (omit it for A4 = 69). Pair with pitchCorrectToMidi(...) to retune to the nearest scale degree.
| Function | Return Type | Description |
|---|---|---|
scaleQuantizeMidi(root, modeMask, midi, scaleReferenceMidi?) | number | Snap a (fractional) MIDI number to the nearest enabled pitch class |
scaleCorrectionSemitones(root, modeMask, midi, scaleReferenceMidi?) | number | Correction (quantized − input), in semitones |
scalePitchClassEnabled(root, modeMask, pitchClass) | boolean | Whether pitchClass (0..11) is enabled relative to root |
scaleMaskForMode(root, mode) | number | The 12-bit modeMask of a mode name ('major', 'minor', 'dorian', ...); a number is a TypeError. scaleMaskForMode(0, 'major') is 0b101010110101 |
Stateful Object Methods
| Object | Methods and contract |
|---|---|
Project tempo and meter | analyzeTempo({ samples, sampleRate, ...options }) returns ranked candidates without editing the project. Read installed maps with tempoSegments() and timeSignatures(). |
Project instrument bounces | bounce(options?) takes the instrument bindings as lists in its options: instruments, builtinInstruments, synthInstruments and sf2Instruments, each binding an instrument per destination. See Project Bounce. |
Project metadata | assistSidecars() returns the opaque sidecars set with setAssistSidecar(...). |
RealtimeEngine graph | setGraph(spec) installs an EngineGraphSpec; graphNodeCount and graphConnectionCount (getters) report its size. |
RealtimeEngine capture and paging | countInEndSample(startSample, bars) resolves the count-in end on the tempo map and returns startSample when bars <= 0. configureCapture(options) sets up recording, and captureStatus() reports it. A file-backed FileClipPageProvider pages a clip's source from disk; destroy the provider when done. |
RealtimeEngine routing | setTrackSends(trackId, sends) and setTrackOutputBus(trackId, busId) replace one lane's sends or output bus (busId 0 is the master mix); the track must already be in the lane list set by setTrackLanes, which accepts at most MAX_TRACK_LANES (32) lanes and throws a RangeError for a longer list. canSetStripSidechain(ref, insertIndex, source) and canSetBusSidechain(busId, insertIndex, source) return a SidechainCheck without changing anything. |
RealtimeEngine offline and clips | primeOfflineParameters(numChannels, blockSize?), resetProcessorState(renderFrame?), tailSamples and graphLatencySamples (getters) support offline renders. upsertClip(clip) and removeClip(clipId) edit clips in place. bounceOffline and freeze render the reported latency ahead and drop it, so frame 0 of the result is the playhead's sample and no manual latency trimming is needed. |
RealtimeEngine automation ids | resolveStripAutomationId(ref, 'faderDb' | 'pan' | 'width') and resolveBusAutomationId(busId, 'faderDb') return the id to automate, where ref is a track id or strip name; resolveStripInsertAutomationId(ref, insertIndex, paramName) does the same for an insert parameter. A track, bus, insert, destination or parameter that does not resolve, or a parameter that is not realtime-safe, throws a RangeError on every resolve*AutomationId. resolveInstrumentAutomationId(destinationId, paramName) takes the destination first. |
RealtimeEngine parameters | setParameter(paramId, value, renderFrame?, { smoothed? }) sets a parameter, ramped when smoothed is true. |
RealtimeEngine MIDI | pushMidiProgram(destinationId, group, channel, program, bank?, renderFrame?) queues a program change; bank is { msb, lsb } or omitted. |
PlaybackRenderer | renderOffline(samples, inChannels) resets the renderer, renders a whole interleaved Float32Array through it and returns the interleaved result (numOutputChannels channels); the result equals renderPlayback for the same configuration, and diagnostics afterwards describes that render. Empty or non-finite input is a RangeError. setHeadOrientation refuses a non-finite or beyond-float32 angle with a RangeError and a non-number with a TypeError. The constructor and renderPlayback take an HrtfSet for hrtf; anything else is a TypeError. |
Mixer routing | setOutputBus(sourceId, busId) routes a source to a bus; flushMeters() folds the pending true-peak stretch into the meter snapshots; call it after the last block of an offline render. |
Project sources | unresolvedAudioSources() returns the descriptors of audio sources that still need decoded PCM, in the order of unresolvedAudioSourceIds(). |
Mixer diagnostics | stripNonFiniteDiscardCount(strip) and busNonFiniteDiscardCount(busId) count processed blocks that discarded non-finite recursive DSP state. Counts are cumulative; bus reads require a compiled bus. vcaGroupCount (a getter) is the VCA group count. |