Node.js Native Feature Extraction
This page lists the feature-extraction, inverse-reconstruction and librosa-compatible functions of the @libraz/libsonare-native package. The names, request shapes and results are the ones of the browser package, so Feature Extraction API has the per-function reference with option tables, and Helpers and Conversions has the librosa-compatible set. For usage, errors and releasing handles see Node.js Native API; the analysis, effects and metering functions are on Node.js Native Analysis, Effects and Utilities.
Usage Examples
Feature Extraction
import { Audio } from '@libraz/libsonare-native';
const audio = Audio.fromFile('music.mp3');
// Spectrogram features
const stftResult = audio.stft({ nFft: 2048, hopLength: 512 });
const mel = audio.melSpectrogram({ nFft: 2048, hopLength: 512, nMels: 128 });
const mfcc = audio.mfcc({ nFft: 2048, hopLength: 512, nMels: 128, nMfcc: 13 });
const chroma = audio.chroma({ nFft: 2048, hopLength: 512 });
// Spectral features
const centroid = audio.spectralCentroid();
const bandwidth = audio.spectralBandwidth();
const rolloff = audio.spectralRolloff();
const flatness = audio.spectralFlatness();
const zcr = audio.zeroCrossingRate();
const rms = audio.rmsEnergy();
// Pitch detection
const pitchYin = audio.pitchYin();
const pitchPyin = audio.pitchPyin();
console.log(`Median F0: ${pitchPyin.medianF0.toFixed(1)} Hz`);Feature Extraction Functions
| Function | Return Type | Description |
|---|---|---|
stft({ samples, sampleRate, nFft?, hopLength?, db? }) | StftResult | Short-Time Fourier Transform; db: true adds the decibel matrix |
melSpectrogram({ samples, sampleRate, nMels?, fminHz?, fmaxHz?, htk?, nFft?, hopLength? }) | MelSpectrogramResult | Mel spectrogram; the result carries nFft, fminHz, fmaxHz as applied, htk beside the power and db matrices |
mfcc({ samples, sampleRate, nMfcc?, lifter?, nMels?, fminHz?, fmaxHz?, htk?, nFft?, hopLength? }) | MfccResult | Mel-Frequency Cepstral Coefficients (lifter default 0 = no liftering); the result carries the Mel parameters and lifter it was computed with |
chroma({ samples, sampleRate, nFft?, hopLength? }) | ChromaResult | Chroma features |
spectralCentroid({ samples, sampleRate, nFft?, hopLength?, db? }) | Float32Array | Spectral centroid per frame |
spectralBandwidth({ samples, sampleRate, nFft?, hopLength?, p? }) | Float32Array | Spectral bandwidth per frame |
spectralRolloff({ samples, sampleRate, rollPercent?, nFft?, hopLength? }) | Float32Array | Spectral rolloff per frame |
spectralFlatness({ samples, sampleRate, nFft?, hopLength?, db? }) | Float32Array | Spectral flatness per frame |
spectralContrast({ samples, sampleRate, nBands?, fminHz?, quantile?, nFft?, hopLength? }) | Matrix2D | Spectral contrast, nBands + 1 rows by nFrames columns |
spectralEdit({ samples, sampleRate, ops, nFft?, hopLength?, window?, healRadiusFrames? }) | Float32Array | Region-based STFT edit with gain, attenuate, mute, or heal ops |
polyFeatures({ samples, sampleRate, order?, nFft?, hopLength? }) | Matrix2D | Per-frame polynomial spectral coefficients |
zeroCrossingRate({ samples, sampleRate, frameLength?, hopLength? }) | Float32Array | Zero-crossing rate per frame |
zeroCrossings({ samples, sampleRate, threshold?, refMagnitude?, pad?, zeroPos? }) | Int32Array | Zero-crossing sample indices |
rmsEnergy({ samples, sampleRate, frameLength?, hopLength? }) | Float32Array | RMS energy per frame |
pitchYin({ samples, sampleRate, frameLength?, hopLength?, f0MinHz?, f0MaxHz?, threshold? }) | PitchResult | YIN pitch estimation; unvoiced f0 stays NaN |
pitchPyin({ samples, sampleRate, frameLength?, hopLength?, f0MinHz?, f0MaxHz?, threshold?, fillNa? }) | PitchResult | pYIN pitch estimation; unvoiced f0 stays NaN unless fillNa is true |
pitchTuning({ frequencies, resolution?, binsPerOctave? }) | number | Tuning offset from frequencies |
estimateTuning({ samples, sampleRate, resolution?, binsPerOctave?, nFft?, hopLength? }) | number | Tuning offset from audio, as a fraction of a bin of binsPerOctave |
tuningToReferenceHz(tuningCents, a4Hz?) / referenceHzToTuning(referenceHz, a4Hz?) | number | Convert between the analysis unit (cents) and a reference pitch in Hz; a4Hz defaults to 440 |
cqt({ samples, sampleRate, hopLength?, fminHz?, nBins?, binsPerOctave?, filterScale? }) | CqtResult | Constant-Q transform magnitude |
vqt({ samples, sampleRate, hopLength?, fminHz?, nBins?, binsPerOctave?, filterScale?, gamma? }) | CqtResult | Variable-Q transform magnitude (gamma controls Q; omit it for the automatic value, 0 is equivalent to CQT, a negative or non-finite value is refused) |
chromaCqt({ samples, sampleRate, hopLength?, nChroma?, binsPerOctave? }) | ChromaResult | Constant-Q chromagram (librosa.feature.chroma_cqt equivalent) |
nnlsChroma({ samples, sampleRate, enableStftBlend?, stftBlendWeight?, stftBlendNFft?, hopLength? }) | Matrix2D | NNLS chromagram (note-activation chroma), 12 rows; hopLength defaults to 512 |
decompose({ s, nComponents, nIter?, beta?, init? }) | DecomposeResult | NMF (non-negative matrix factorization) factor matrices w and h from a spectrogram Matrix2D, with selectable init ('random' default, 'nndsvd') |
decomposeStems(request) | DecomposeStemsResult | NMF separation that carries the original phase, so each component is directly listenable. Request-only — takes DecomposeStemsRequest |
decomposeStemsLinked(request) | DecomposeStemsLinkedResult | Shared NMF model and soft mask for one or more same-length channels (maximum 64); applies each mask to each channel's original complex spectrum, preserving interchannel level and phase. Request-only — returns components[k][c] with the same defaults as decomposeStems; one channel is bit-identical |
noteSegments(request) | NoteSegment[] | Segment a caller-supplied monophonic F0 track into stable note regions. Request-only — takes NoteSegmentsRequest |
hybridCqt({ samples, sampleRate, hopLength?, fminHz?, nBins?, binsPerOctave?, filterScale? }) | CqtResult | Hybrid CQT magnitude (true CQT in low bins, pseudo-CQT in high bins) |
pseudoCqt({ samples, sampleRate, hopLength?, fminHz?, nBins?, binsPerOctave?, filterScale? }) | CqtResult | Approximate (pseudo) CQT magnitude (single FFT) |
bassChroma({ samples, sampleRate, hopLength?, nChroma? }) | ChromaResult | Bass-focused chroma (low-register pitch-class distribution) |
chromaCens({ samples, sampleRate, hopLength?, nChroma?, binsPerOctave? }) | ChromaResult | CENS energy-normalized/smoothed chroma |
onsetStrengthMulti({ samples, sampleRate, nBands?, nFft?, hopLength?, nMels? }) | Matrix2D | Multi-band onset strength (nBands default 3; nBands rows by nFrames columns) |
nnFilter({ s, aggregate?, k?, width? }) | Matrix2D | Nearest-neighbor filtering |
onsetStrength({ samples, sampleRate, nFft?, hopLength?, nMels? }) | Float32Array | Onset strength envelope — how sharply energy rises per frame; the input to the tempogram family |
Use a finite, nonnegative lifter for forward and inverse MFCC. Zero disables liftering. Inverse MFCC also refuses a negative value that rounds to zero in float32.
The inverse transforms (melToStft, melToAudio, mfccToMel, mfccToAudio, cqtToAudio, vqtToAudio) are documented below.
Common defaults: nFft=2048, hopLength=512, nMels=128, nMfcc=20, pitch f0MinHz=65.0, f0MaxHz=2093.0, threshold=0.1, and rollPercent=0.85.
CQT/VQT use fminHz=32.70319566 (C1), nBins=84, and binsPerOctave=12. Omitting VQT's gamma selects automatic ERB-derived bandwidth. chromaCqt defaults to nChroma=12 and binsPerOctave=36; chromaCens defaults to nChroma=12 and binsPerOctave=36, and bassChroma to nChroma=12. onsetStrengthMulti defaults to nBands=3. decompose defaults to nIter=50, beta=2, and init='random'.
decompose versus decomposeStems
decompose(...) returns the W/H factors of a magnitude spectrogram. Those factors carry no phase, so reconstructing from them needs a phase estimator, and an estimated phase does not hold up as a stem. decomposeStems(...) builds a per-component soft mask from the same factorization and applies it to the original complex spectrogram, so every component keeps the source's phase. The masks sum to one wherever the model has energy and the inverse STFT is linear, so the components sum back to the input.
maskPower sets how hard the mask separates: 1 (the default) keeps the magnitude ratio, 2 is the Wiener-style power ratio, which separates harder at the cost of more artifacts on overlapping partials. decomposeStems defaults to nComponents=4, nFft=2048, hopLength=512, nIter=100, beta=2, and init='random', and returns components — one signal per component, each the length of the input — alongside the w/h matrices and sampleRate.
For multichannel input, decomposeStemsLinked({ channels, sampleRate, ... }) fits one NMF model and one mask set from the channels' averaged magnitudes, then applies each mask unchanged to each channel's original complex spectrum. This preserves interchannel level and phase. channels must contain at least one same-length Float32Array and at most 64 channels. The result uses components[k][c]; w and h describe the shared factorisation. Its option defaults match decomposeStems, and a one-channel call is bit-identical.
import { decomposeStemsLinked } from '@libraz/libsonare-native';
const linked = decomposeStemsLinked({
channels: [leftChannel, rightChannel],
sampleRate,
});
const firstLeft = linked.components[0][0];
const firstRight = linked.components[0][1];NNDSVD factors will not match single-precision ones
NNDSVD seeding is computed in double precision. A magnitude spectrogram's trailing singular vectors sit at single precision's noise floor, so a float seed would depend on summation order, and wasm32 and arm64 would answer with different components; the double-precision seed makes the result reproducible across builds. Shapes, non-negativity and reconstruction quality are unaffected — this is reproducibility, not accuracy — but stored factors, or a stem render made with a single-precision seed, will not match.
noteSegments
noteSegments({ f0Hz, voicedProb, frameRate, ... }) segments a caller-supplied monophonic F0 track into stable note regions, one NoteSegment per region with frameStart, frameEnd, startSec, endSec, and medianCents. The tuning fields are segmentationThresholdCents (default 50), minNoteMs (default 30), referenceHz (default 440), and voicedThreshold (default 0.5), the value of voicedProb at or above which a frame counts as voiced. A negative or non-finite segmentationThresholdCents or minNoteMs is a RangeError, and a minNoteMs longer than the track returns no notes.
Do not feed pYIN's voicedProb straight in
voicedProb is the frame's voiced observation mass, and for a fixed frame length it rises with F0 rather than tracking confidence. A fixed threshold therefore silently returns no segments at all for low-register material. Pass pitchPyin's voicedFlag converted to 0/1, or lower voicedThreshold.
Inverse Reconstruction Functions
Reconstruct a spectrum or audio from a mel spectrogram or MFCC matrix. Phase is estimated with Griffin-Lim, so the round-trip is lossy — see Inverse Features.
All six take a single request object. A mel spectrogram, MFCC or CQT/VQT matrix is a Matrix2D ({ data, rows, cols }), which is what the forward transforms return.
| Function | Return Type | Description |
|---|---|---|
melToStft({ power, sampleRate?, nFft?, fminHz?, fmaxHz?, htk? }) | Matrix2D | Linear STFT magnitude from a mel power spectrogram |
melToAudio({ power, sampleRate?, nFft?, hopLength?, fminHz?, fmaxHz?, nIter?, htk? }) | Float32Array | Audio from a mel spectrogram (Griffin-Lim) |
mfccToMel({ coefficients, nMels?, lifter? }) | Matrix2D | Mel spectrogram from MFCC coefficients |
mfccToAudio({ coefficients, nMels?, sampleRate?, nFft?, hopLength?, fminHz?, fmaxHz?, nIter?, htk?, lifter? }) | Float32Array | Audio from MFCC coefficients; lifter defaults to 0 |
cqtToAudio({ magnitude, sampleRate, hopLength?, fminHz?, binsPerOctave?, nIter? }) | Float32Array | Audio from a CQT magnitude matrix (Griffin-Lim) |
vqtToAudio({ magnitude, sampleRate, hopLength?, fminHz?, binsPerOctave?, gamma?, nIter? }) | Float32Array | Audio from a VQT magnitude matrix (Griffin-Lim) |
librosa-Compatible Helpers
These mirror the corresponding librosa functions — see librosa Compatibility for the full mapping.
What each helper is for
preemphasis/deemphasis— classic one-tap IIR pre-processing on the waveform.trimSilence/splitSilence— trim leading/trailing silence or split on silent gaps.frameSignal/padCenter/fixLength/fixFrames— framing and size-alignment utilities for fixed-frame DSP.peakPick/vectorNormalize— peak detection on 1-D signals and vector-norm normalization.pcen— dynamic range compression for mel spectrograms.tonnetz— projects chroma into a 6-D harmonic space.tempogram/plp— time-varying tempo representation and dominant local pulse.
| Function | Return Type | Description |
|---|---|---|
preemphasis({ samples, sampleRate, coef?, zi? }) | Float32Array | Pre-emphasis filter |
deemphasis({ samples, sampleRate, coef?, zi? }) | Float32Array | Inverse pre-emphasis |
trimSilence({ samples, sampleRate, topDb?, frameLength?, hopLength? }) | { audio: Float32Array; startSample: number; endSample: number } | librosa.effects.trim, distinct from threshold trim(...) |
splitSilence({ samples, sampleRate, topDb?, frameLength?, hopLength? }) | Int32Array | librosa.effects.split — flat [start0, end0, start1, end1, ...] |
splitSilenceCommon({ signals, topDb?, frameLength?, hopLength? }) | Int32Array | The cut points several takes of one part agree are silent. Same flat layout; takes of unequal length need no padding |
frameSignal({ samples, sampleRate, frameLength, hopLength }) | Matrix2D | librosa.util.frame (row-major) |
padCenter({ values, targetSize, padValue? }) | Float32Array | librosa.util.pad_center |
fixLength({ values, targetSize, padValue? }) | Float32Array | librosa.util.fix_length |
fixFrames({ frames, xMin?, xMax?, pad? }) | Int32Array | librosa.util.fix_frames |
peakPick({ values, preMax, postMax, preAvg, postAvg, delta, wait }) | Int32Array | librosa.util.peak_pick |
vectorNormalize({ values, norm?, threshold? }) | Float32Array | librosa.util.normalize. norm: 'max', 'l1', 'l2' or 'power'; threshold defaults to 0 (the library's tiny-norm guard) |
pcen({ values, sampleRate?, hopLength?, timeConstant?, gain?, bias?, power?, eps? }) | Matrix2D | librosa.pcen (mel Matrix2D input) |
tonnetz({ chromagram }) | Matrix2D | librosa.feature.tonnetz (6 rows) |
tempogram({ onsetEnvelope, sampleRate?, hopLength?, winLength?, mode?, center?, norm? }) | Matrix2D | librosa.feature.tempogram; mode is 'autocorrelation' (default) or 'cosine' |
fourierTempogram({ onsetEnvelope, sampleRate?, hopLength?, winLength?, center? }) | Matrix2D | librosa.feature.fourier_tempogram |
cyclicTempogram({ onsetEnvelope, sampleRate, hopLength?, winLength?, bpmMin?, nBins? }) | Matrix2D | Cyclic (tempo-octave-invariant) tempogram; defaults winLength=384, bpmMin=60, nBins=60 |
tempogramRatio({ tempogram, sampleRate?, hopLength?, factors? }) | Float32Array | librosa.feature.tempogram_ratio; factors default to [0.5, 1, 2, 3, 4] |
plp({ onsetEnvelope, sampleRate?, hopLength?, bpmMin?, bpmMax?, winLength? }) | Float32Array | librosa.beat.plp |