Skip to content

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 ​

typescript
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 ​

typescript
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.

FunctionReturn TypeDescription
detectBpm({ samples, sampleRate, bpmMin?, bpmMax? })number or undefinedTempo in BPM, or undefined when no tempo is found
detectKey({ samples, sampleRate, ...options })KeyDetectionRoot (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? })Float32ArrayBeat timestamps
detectOnsets({ samples, sampleRate, ...options })Float32ArrayOnset timestamps. options: nFft, hopLength, threshold, preMax, postMax, preAvg, postAvg, delta, wait, backtrack, backtrackRange
detectChords({ samples, sampleRate, ...options })ChordAnalysisResultChord 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 })Float32ArrayDownbeat (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 })AnalysisResultAll-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 })MeterEstimateScore beat-level observations without audio or re-running analysis. Request-only — takes EstimateMeterRequest
analyzeBpm({ samples, sampleRate, ...options })BpmAnalysisResultTempo 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 })RhythmResultTime signature, groove, syncopation. options: bpmMin, bpmMax, startBpm, nFft, hopLength
analyzeDynamics({ samples, sampleRate, ...options })DynamicsResultDynamic 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 })TimbreResultBrightness, warmth, density, roughness, complexity, plus per-window timbreOverTime. options: nFft, hopLength, nMels, nMfcc, windowSec
analyzeSections({ samples, sampleRate, ...options })SectionAnalysisStructural 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 })BoundaryResultStructural 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 })MelodyResultLead-melody contour (F0 per frame). options: f0MinHz, f0MaxHz, frameLength, hopLength, threshold, usePyin, center
detectAcoustic({ samples, sampleRate, ...options })AcousticResultRoom 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? })AcousticResultRoom acoustics from a measured impulse response; minDecayDb controls the decay-fit threshold (default 30)
estimateRoom({ samples, sampleRate, ...options })RoomEstimateResultEquivalent-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 })RirResultMono 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? })RoomGeometryTurns 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 })RoomMorphResultOffline creative morph toward a target room; read morphed samples from .audio, with .sampleRate and .diagnostics alongside them
roomMorphStereo({ left, right, sampleRate, receiverSpacingM?, ...options })RoomMorphStereoResultStereo 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 })LufsResultIntegrated, final momentary/short-term windows, their EBU R128 maxima, and loudness range (loudnessRangeLu)
lufsMultichannel({ channels, sampleRate })LufsResultChannel-weighted multichannel loudness from planar channels
lufsSeriesMultichannel({ channels, sampleRate })LufsSeriesResultMomentary and short-term loudness series of a multichannel signal
ebur128LoudnessRangeLu({ samples, sampleRate })numberStandards-compliant EBU R128 loudness range (LRA) in LU
momentaryLufs({ samples, sampleRate })Float32ArrayMomentary loudness (400 ms) per step
shortTermLufs({ samples, sampleRate })Float32ArrayShort-term loudness (3 s) per step
version()stringLibrary version
voiceChangerAbiVersion()numberABI version of the realtime voice-changer POD config; separate from preset JSON schemaVersion
voiceCharacterPresetId(ordinal)VoicePresetIdCanonical voice-character preset ID of an ordinal; an out-of-range ordinal throws
realtimeVoiceChangerPresetConfig(preset)RealtimeVoiceChangerConfigResolved 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:

OptionDefaultDescription
nFft / hopLength2048 / 512STFT resolution shared across the pipeline. nFft is samples at 22050 Hz, rescaled to the input rate; hopLength is samples of the input
bpmMin / bpmMax / startBpm60 / 200 / 120Tempo search range and prior
useTriadsOnlytrueRestrict the chord search to triads
useHpssfalseApply harmonic-percussive separation before the chord chroma
chromaHighPassHz80Chroma high-pass cutoff in Hz (0 disables)
useBassWeightedtrueBass-weighted chroma combination
chromaHopMultiplier4Chroma hop multiplier; larger is faster
useChordHmm / useChordKeyContext / chordHmmBeamWidth / detectChordInversionstrue / false / 24 / falseChord post-processing: HMM smoothing, key-biased transitions, the HMM beam width, and slash-chord bass estimation
adaptiveTempofalseTrack a locally updated tempo prior through beat tracking
tempoUpdateIntervalBeats8Local tempo context length in beats; read only when adaptiveTempo is set
computeTempoCurvefalseDecode 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
meterDenominator4Beat 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.

typescript
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
FieldDefaultDescription
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
denominator4Beat unit reported for the detected meter, as requested: a six accented 3+3 comes back with this denominator and grouping [3, 3]
compoundSubdivisionThreshold0.5Mean measured subdivision accent relative to mean beat accent at which a six or three is read as compound
downbeatWeight / measureWeight / subdivisionWeight1 / 0.5 / 0.15Scoring weights for the first beat of each measure, measure-to-measure accent agreement, and the subdivision pattern
DETECTOR · BEAT / METER-ESTIMATEIDLE
Meter estimation — ranking time signatures by confidence

Meter estimation scores candidate time signatures over the detected beats: each beat's accent is read from the onset envelope, and 3, 4 and 6 are tried as bar lengths. The result is a ranked list with a confidence for each, not a single verdict — the confidences are shares of the total support, so they read as a breakdown rather than as a probability of being right. Four bars of a plain 4/4 groove here, so 4 takes most of the support and 6 keeps the rest, since every other downbeat also starts a six-beat span. Switch to Beats to see the pulse the estimate was scored on. A clip with fewer than eight detected beats reports that no search ran at all, rather than guessing.

Detect

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.
  • searched is false when the beat series was under eight beats. Every other field then carries a fixed fallback rather than a result — including timeSignature.confidence, which reads 0, so an unchecked read degrades toward "no idea" rather than toward a middling detection. Read searched before 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.

FunctionReturn TypeDescription
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 ​

FunctionReturn TypeDescription
hpss({ samples, sampleRate, kernelHarmonic?, kernelPercussive?, nFft?, hopLength?, hardMask?, withResidual? })HpssResultHarmonic-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 })Float32ArrayExtract harmonic component
percussive({ samples, sampleRate })Float32ArrayExtract percussive component
timeStretch({ samples, sampleRate, speedRatio, nFft?, hopLength? })Float32ArrayTime-stretch without pitch change; defaults to nFft=2048, hopLength=512
phaseVocoder({ samples, sampleRate, speedRatio, nFft?, hopLength? })Float32ArrayDirect phase-vocoder time scaling
pitchShift({ samples, sampleRate, pitchSemitones, nFft?, hopLength? })Float32ArrayPitch-shift without tempo change; defaults to nFft=2048, hopLength=512
remix({ samples, sampleRate, intervals, alignZeros? })Float32ArrayReorder or concatenate sample intervals
remixAlignedIntervals({ samples, sampleRate, intervals, alignZeros? })Int32ArrayThe 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? })Float32ArrayNormalize 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? })NormalizeStereoResultNormalize a channel pair on a level measured across both channels. Request-only
trim({ samples, sampleRate, thresholdDb?, frameLength?, hopLength? })Float32ArrayTrim silence (defaults: -60.0 dB, frameLength=2048, hopLength=512)
resample({ samples, sampleRate, targetSampleRate })Float32ArrayResample to target sample rate
pitchCorrectToMidi({ samples, sampleRate, currentMidi, targetMidi })Float32ArrayRetune 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? })Float32ArrayRetune 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? })AutoTuneResultTune 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 })Float32ArrayTime-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? })Float32ArrayMove a note span to another onset; exactly one target field is required
voiceChange({ samples, sampleRate, pitchSemitones?, formantFactor?, formantMode? })Float32ArrayPitch + 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:

typescript
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 ​

FunctionReturn TypeDescription
transcribe({ samples, sampleRate, ...options })TranscribeResultMono 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? })AlignTakeToReferenceResultWarp anchors that map a take onto the reference timeline. takeSampleRate defaults to sampleRate
chordSymbolFromAnalysis(chord)ChordSymbolFieldsConverts a detectChords or analyze chord into the fields of a chord annotation for Project.annotateChords. See Project MIDI
keyModeFromAnalysis(mode)ProjectKeyModeConverts 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 ​

FunctionDescription
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.

FunctionReturn TypeDescription
meteringPeakDb({ samples, sampleRate })numberSample peak (dBFS)
meteringRmsDb({ samples, sampleRate })numberRMS level (dBFS)
meteringCrestFactorDb({ samples, sampleRate })number or undefinedCrest factor, peak − RMS (dB). undefined for silence
meteringCrestFactorDbStereo({ left, right, sampleRate })number or undefinedCrest factor across both channels (dB). Request-only; undefined when both channels are silent
meteringDcOffset({ samples, sampleRate })numberMean (DC) offset, linear amplitude
meteringTruePeakDbtp({ samples, sampleRate, oversampleFactor? })numberInter-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? })ClippingReportClipped-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? })DynamicRangeReportSliding-window dynamic range (omit for defaults: window 3 s, hop 1 s, low 0.10, high 0.95)
meteringStereoCorrelation({ left, right, sampleRate })number or undefinedUncentered correlation (cosine similarity), −1..1; undefined when either channel has zero energy
meteringStereoWidth({ left, right, sampleRate })number or undefinedSide-to-mid RMS amplitude ratio. Infinity when only mid is silent; undefined when mid and side are silent
meteringVectorscope({ left, right, sampleRate })VectorscopeReportPer-sample mid/side point series
meteringPhaseScope({ left, right, sampleRate })PhaseScopeReportPhase-scope point series plus summary stats
meteringSpectrum({ samples, sampleRate, nFft?, applyOctaveSmoothing?, octaveFraction?, dbRef?, dbAmin? })SpectrumReportWelch-averaged magnitude/power/dB spectrum over the whole signal (50%-overlapping Hann frames, averaged)
meteringSpectrumFrame({ samples, sampleRate, startSample?, ...spectrumOptions })SpectrumReportTrue 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? })numberFraction of analysis frames whose RMS is below thresholdDb (defaults: -45 dBFS, frameLength=1024, hopLength=256)
waveformPeaks({ channels, samplesPerBucket? })WaveformPeaksReportPer-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.

FunctionReturn TypeDescription
scaleQuantizeMidi(root, modeMask, midi, scaleReferenceMidi?)numberSnap a (fractional) MIDI number to the nearest enabled pitch class
scaleCorrectionSemitones(root, modeMask, midi, scaleReferenceMidi?)numberCorrection (quantized − input), in semitones
scalePitchClassEnabled(root, modeMask, pitchClass)booleanWhether pitchClass (0..11) is enabled relative to root
scaleMaskForMode(root, mode)numberThe 12-bit modeMask of a mode name ('major', 'minor', 'dorian', ...); a number is a TypeError. scaleMaskForMode(0, 'major') is 0b101010110101

Stateful Object Methods ​

ObjectMethods and contract
Project tempo and meteranalyzeTempo({ samples, sampleRate, ...options }) returns ranked candidates without editing the project. Read installed maps with tempoSegments() and timeSignatures().
Project instrument bouncesbounce(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 metadataassistSidecars() returns the opaque sidecars set with setAssistSidecar(...).
RealtimeEngine graphsetGraph(spec) installs an EngineGraphSpec; graphNodeCount and graphConnectionCount (getters) report its size.
RealtimeEngine capture and pagingcountInEndSample(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 routingsetTrackSends(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 clipsprimeOfflineParameters(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 idsresolveStripAutomationId(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 parameterssetParameter(paramId, value, renderFrame?, { smoothed? }) sets a parameter, ramped when smoothed is true.
RealtimeEngine MIDIpushMidiProgram(destinationId, group, channel, program, bank?, renderFrame?) queues a program change; bank is { msb, lsb } or omitted.
PlaybackRendererrenderOffline(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 routingsetOutputBus(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 sourcesunresolvedAudioSources() returns the descriptors of audio sources that still need decoded PCM, in the order of unresolvedAudioSourceIds().
Mixer diagnosticsstripNonFiniteDiscardCount(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.