Skip to content

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 ​

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

FunctionReturn TypeDescription
stft({ samples, sampleRate, nFft?, hopLength?, db? })StftResultShort-Time Fourier Transform; db: true adds the decibel matrix
melSpectrogram({ samples, sampleRate, nMels?, fminHz?, fmaxHz?, htk?, nFft?, hopLength? })MelSpectrogramResultMel 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? })MfccResultMel-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? })ChromaResultChroma features
spectralCentroid({ samples, sampleRate, nFft?, hopLength?, db? })Float32ArraySpectral centroid per frame
spectralBandwidth({ samples, sampleRate, nFft?, hopLength?, p? })Float32ArraySpectral bandwidth per frame
spectralRolloff({ samples, sampleRate, rollPercent?, nFft?, hopLength? })Float32ArraySpectral rolloff per frame
spectralFlatness({ samples, sampleRate, nFft?, hopLength?, db? })Float32ArraySpectral flatness per frame
spectralContrast({ samples, sampleRate, nBands?, fminHz?, quantile?, nFft?, hopLength? })Matrix2DSpectral contrast, nBands + 1 rows by nFrames columns
spectralEdit({ samples, sampleRate, ops, nFft?, hopLength?, window?, healRadiusFrames? })Float32ArrayRegion-based STFT edit with gain, attenuate, mute, or heal ops
polyFeatures({ samples, sampleRate, order?, nFft?, hopLength? })Matrix2DPer-frame polynomial spectral coefficients
zeroCrossingRate({ samples, sampleRate, frameLength?, hopLength? })Float32ArrayZero-crossing rate per frame
zeroCrossings({ samples, sampleRate, threshold?, refMagnitude?, pad?, zeroPos? })Int32ArrayZero-crossing sample indices
rmsEnergy({ samples, sampleRate, frameLength?, hopLength? })Float32ArrayRMS energy per frame
pitchYin({ samples, sampleRate, frameLength?, hopLength?, f0MinHz?, f0MaxHz?, threshold? })PitchResultYIN pitch estimation; unvoiced f0 stays NaN
pitchPyin({ samples, sampleRate, frameLength?, hopLength?, f0MinHz?, f0MaxHz?, threshold?, fillNa? })PitchResultpYIN pitch estimation; unvoiced f0 stays NaN unless fillNa is true
pitchTuning({ frequencies, resolution?, binsPerOctave? })numberTuning offset from frequencies
estimateTuning({ samples, sampleRate, resolution?, binsPerOctave?, nFft?, hopLength? })numberTuning offset from audio, as a fraction of a bin of binsPerOctave
tuningToReferenceHz(tuningCents, a4Hz?) / referenceHzToTuning(referenceHz, a4Hz?)numberConvert between the analysis unit (cents) and a reference pitch in Hz; a4Hz defaults to 440
cqt({ samples, sampleRate, hopLength?, fminHz?, nBins?, binsPerOctave?, filterScale? })CqtResultConstant-Q transform magnitude
vqt({ samples, sampleRate, hopLength?, fminHz?, nBins?, binsPerOctave?, filterScale?, gamma? })CqtResultVariable-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? })ChromaResultConstant-Q chromagram (librosa.feature.chroma_cqt equivalent)
nnlsChroma({ samples, sampleRate, enableStftBlend?, stftBlendWeight?, stftBlendNFft?, hopLength? })Matrix2DNNLS chromagram (note-activation chroma), 12 rows; hopLength defaults to 512
decompose({ s, nComponents, nIter?, beta?, init? })DecomposeResultNMF (non-negative matrix factorization) factor matrices w and h from a spectrogram Matrix2D, with selectable init ('random' default, 'nndsvd')
decomposeStems(request)DecomposeStemsResultNMF separation that carries the original phase, so each component is directly listenable. Request-only — takes DecomposeStemsRequest
decomposeStemsLinked(request)DecomposeStemsLinkedResultShared 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? })CqtResultHybrid CQT magnitude (true CQT in low bins, pseudo-CQT in high bins)
pseudoCqt({ samples, sampleRate, hopLength?, fminHz?, nBins?, binsPerOctave?, filterScale? })CqtResultApproximate (pseudo) CQT magnitude (single FFT)
bassChroma({ samples, sampleRate, hopLength?, nChroma? })ChromaResultBass-focused chroma (low-register pitch-class distribution)
chromaCens({ samples, sampleRate, hopLength?, nChroma?, binsPerOctave? })ChromaResultCENS energy-normalized/smoothed chroma
onsetStrengthMulti({ samples, sampleRate, nBands?, nFft?, hopLength?, nMels? })Matrix2DMulti-band onset strength (nBands default 3; nBands rows by nFrames columns)
nnFilter({ s, aggregate?, k?, width? })Matrix2DNearest-neighbor filtering
onsetStrength({ samples, sampleRate, nFft?, hopLength?, nMels? })Float32ArrayOnset 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.

A/B PROCESS · HPSSIDLE
Stem decomposition — pulling the percussive part out of a mix

A sustained pad chord bed with sharp broadband hits on every beat (Full mix). The stage applied here is HPSS decomposition, and the B side is its percussive component alone: the hits survive as short vertical events while the pad's steady spectral lines are pushed out. That is one stem of a two-way split, not a full multi-stem separation (Percussive). Both averaged spectra are drawn together so you can see what the split kept. Flip Compare to audition the mix against the stem it was decomposed into.

Compare

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.

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

PARAM SWEEP · GRIFFIN-LIMIDLE
Griffin-Lim — how iterations recover phase

This example first estimates a linear-frequency magnitude spectrum from mel-band power, then uses Griffin–Lim iterations to estimate phase. The mel transform loses frequency detail and the phase is not unique, so this cannot recover the original waveform exactly. Compare iteration counts and listen for changes in smearing and hollow tone; more iterations do not guarantee a perceptual improvement.

Preview
Switching during playback restarts the selected audio from the beginning.Processed
Iterations
16 iter

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.

FunctionReturn TypeDescription
melToStft({ power, sampleRate?, nFft?, fminHz?, fmaxHz?, htk? })Matrix2DLinear STFT magnitude from a mel power spectrogram
melToAudio({ power, sampleRate?, nFft?, hopLength?, fminHz?, fmaxHz?, nIter?, htk? })Float32ArrayAudio from a mel spectrogram (Griffin-Lim)
mfccToMel({ coefficients, nMels?, lifter? })Matrix2DMel spectrogram from MFCC coefficients
mfccToAudio({ coefficients, nMels?, sampleRate?, nFft?, hopLength?, fminHz?, fmaxHz?, nIter?, htk?, lifter? })Float32ArrayAudio from MFCC coefficients; lifter defaults to 0
cqtToAudio({ magnitude, sampleRate, hopLength?, fminHz?, binsPerOctave?, nIter? })Float32ArrayAudio from a CQT magnitude matrix (Griffin-Lim)
vqtToAudio({ magnitude, sampleRate, hopLength?, fminHz?, binsPerOctave?, gamma?, nIter? })Float32ArrayAudio 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.
FunctionReturn TypeDescription
preemphasis({ samples, sampleRate, coef?, zi? })Float32ArrayPre-emphasis filter
deemphasis({ samples, sampleRate, coef?, zi? })Float32ArrayInverse 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? })Int32Arraylibrosa.effects.split — flat [start0, end0, start1, end1, ...]
splitSilenceCommon({ signals, topDb?, frameLength?, hopLength? })Int32ArrayThe 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 })Matrix2Dlibrosa.util.frame (row-major)
padCenter({ values, targetSize, padValue? })Float32Arraylibrosa.util.pad_center
fixLength({ values, targetSize, padValue? })Float32Arraylibrosa.util.fix_length
fixFrames({ frames, xMin?, xMax?, pad? })Int32Arraylibrosa.util.fix_frames
peakPick({ values, preMax, postMax, preAvg, postAvg, delta, wait })Int32Arraylibrosa.util.peak_pick
vectorNormalize({ values, norm?, threshold? })Float32Arraylibrosa.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? })Matrix2Dlibrosa.pcen (mel Matrix2D input)
tonnetz({ chromagram })Matrix2Dlibrosa.feature.tonnetz (6 rows)
tempogram({ onsetEnvelope, sampleRate?, hopLength?, winLength?, mode?, center?, norm? })Matrix2Dlibrosa.feature.tempogram; mode is 'autocorrelation' (default) or 'cosine'
fourierTempogram({ onsetEnvelope, sampleRate?, hopLength?, winLength?, center? })Matrix2Dlibrosa.feature.fourier_tempogram
cyclicTempogram({ onsetEnvelope, sampleRate, hopLength?, winLength?, bpmMin?, nBins? })Matrix2DCyclic (tempo-octave-invariant) tempogram; defaults winLength=384, bpmMin=60, nBins=60
tempogramRatio({ tempogram, sampleRate?, hopLength?, factors? })Float32Arraylibrosa.feature.tempogram_ratio; factors default to [0.5, 1, 2, 3, 4]
plp({ onsetEnvelope, sampleRate?, hopLength?, bpmMin?, bpmMax?, winLength? })Float32Arraylibrosa.beat.plp