Skip to content

JavaScript/TypeScript Helpers and Conversions ​

librosa-parity helper functions for the libsonare JavaScript/TypeScript package, followed by scale quantization, unit conversion, resampling, and harmonic functions from a chord list; see Analysis API for BPM/key/beat detection and the all-in-one analyze() call.

librosa-Compatible Helpers ​

These librosa-parity helpers match the corresponding librosa functions and are exposed across the WASM, Node, and Python bindings. The signatures are below; for the librosa function each one maps to argument-for-argument, and when to reach for it, see librosa Compatibility.

Python uses the same function names in snake_case. The segmentation family keeps its segment_ prefix: segment_cross_similarity, segment_recurrence_matrix, segment_recurrence_to_lag, segment_lag_to_recurrence, segment_path_enhance, segment_subsegment, segment_agglomerative.

Pre-emphasis / De-emphasis ​

typescript
function preemphasis(request: PreemphasisRequest): Float32Array  // { samples, sampleRate, coef? (default 0.97), zi? }
function deemphasis(request: DeemphasisRequest): Float32Array
// both also take (samples, sampleRate, options?)

zi provides an initial condition (a previous frame's tail) when streaming.

Test-signal generation ​

Deterministic signals for fixtures, calibration, and click tracks. No asset files are needed.

typescript
function tone(request?: ToneRequest): Float32Array
function chirp(request?: ChirpRequest): Float32Array
function clicks(request: ClicksRequest): Float32Array

Spectral reconstruction and pitch candidates ​

typescript
function griffinLim(request: GriffinLimRequest): Float32Array
function reassignedSpectrogram(request: ReassignedSpectrogramRequest): ReassignedSpectrogramResult
function piptrack(request: PiptrackRequest): PiptrackResult
function melDelta(request: MelDeltaRequest): Matrix2D
function spectralFlux(request: SpectralFluxRequest): Float32Array
function onsetBacktrack(request: OnsetBacktrackRequest): Int32Array

griffinLim reconstructs audio from an STFT magnitude matrix; melToAudio and mfccToAudio are the mel-domain wrappers around it. onsetBacktrack moves detected onset frames back to the preceding energy minimum, which is what you want before slicing at an onset.

spectralBandwidth takes a configurable Minkowski exponent p (positional argument 5, or p on the request object) rather than assuming p = 2.

Structure and self-similarity ​

The segmentation family builds the matrices structural analysis is made of.

typescript
function segmentCrossSimilarity(request: SegmentCrossSimilarityRequest): Matrix2D
function segmentRecurrenceMatrix(request: SegmentRecurrenceMatrixRequest): Matrix2D
function segmentRecurrenceToLag(request: SegmentRecurrenceToLagRequest): Matrix2D
function segmentLagToRecurrence(request: SegmentLagToRecurrenceRequest): Matrix2D
function segmentPathEnhance(request: SegmentPathEnhanceRequest): Matrix2D
function segmentSubsegment(request: SegmentSubsegmentRequest): Int32Array
function segmentAgglomerative(request: SegmentAgglomerativeRequest): Int32Array

segmentRecurrenceToLag returns the lag-by-time layout, as librosa does: with the default pad: true an n × n recurrence gives a 2n × n matrix (n × n with pad: false), and segmentLagToRecurrence takes either height (lags equal to rows, or twice rows).

analyzeSections(...) is the packaged answer for "where are the sections". Reach for these when you want the intermediate matrices, for example to draw a self-similarity plot or to run your own boundary detection over an enhanced recurrence matrix.

Note segmentation ​

Turn a monophonic F0 track into stable note regions. Pass a track you already have (from pitchYin / pitchPyin, or from your own tracker) together with the frame cadence that produced it.

typescript
interface NoteSegmentsRequest {
  f0Hz: Float32Array;
  /** Frames per second of the supplied track. */
  frameRate: number;
  /** Per-frame voiced flags; takes precedence over `voicedProb`. */
  voiced?: VoicedFlags;
  /** Per-frame values in [0, 1], read only when `voiced` is omitted. */
  voicedProb?: Float32Array;
  segmentationThresholdCents?: number;  // default 50
  minNoteMs?: number;                   // default 30
  referenceHz?: number;                 // default 440 (A4)
  /** Voicing threshold applied to `voicedProb`. */
  voicedThreshold?: number;             // default 0.5
}

function noteSegments(request: NoteSegmentsRequest): Array<{
  frameStart: number;    // half-open frame bounds: [frameStart, frameEnd)
  frameEnd: number;
  startSec: number;
  endSec: number;
  medianCents: number;
}>

f0Hz and the voiced series must be the same non-zero length. Zero-Hz frames and voicedProb values below voicedThreshold (default 0.5) count as unvoiced and break a note.

referenceHz is in Hz. To start from an analysis tuningCents, convert with tuningToReferenceHz(tuningCents, a4Hz = 440); referenceHzToTuning(hz, a4Hz = 440) is the inverse (tuningToReferenceHz(25) is about 446.4 Hz).

Do not pass pitchPyin's voicedProb here

Despite the field name, this is not the place for pYIN's voicedProb. That value is the frame's voiced observation mass, and for a fixed frame length it rises with F0, so it tracks pitch height, not confidence. Fed to a fixed threshold it silently returns no segments at all for low-register material: a steady tone below roughly C5 never reaches 0.5, so every frame reads as unvoiced and the function returns an empty array with no error to explain it.

Pass the flags instead (PitchResult.voicedFlag, as voiced) or, if you must use a probability-like series, lower voicedThreshold to suit the register you are working in.

Silence Trim / Split ​

typescript
// Both take a request object, or (samples, sampleRate, options?)
function trimSilence(request: {
  samples: Float32Array;
  sampleRate: number;
  topDb?: number;        // default 60
  frameLength?: number;  // default 2048
  hopLength?: number;    // default 512
}): { audio: Float32Array; startSample: number; endSample: number }

function splitSilence(request: SplitSilenceRequest): Int32Array  // same fields; flat [start0, end0, start1, end1, ...]

function splitSilenceCommon(request: {
  signals: Float32Array[];
  topDb?: number;         // default 60
  frameLength?: number;   // default 2048
  hopLength?: number;     // default 512
}): Int32Array            // same flat pair layout

trimSilence (librosa.effects.trim) uses frame RMS and a topDb distance below the peak RMS, returning the trimmed audio plus the original [startSample, endSample) range. It differs from the simpler trim({ samples, sampleRate, thresholdDb }). splitSilence (librosa.effects.split) returns non-silent intervals as sample-index pairs.

splitSilenceCommon answers the same question for several takes of one part at once. What takes have in common is the silence, not the sound: one take breathes where another sustains, so a cut point chosen from a single take lands mid-phrase in the others. It returns the union of what splitSilence reports for each signal, merged where intervals touch. Every gap between the returned intervals is therefore quiet in all of them simultaneously, and a cut placed there is safe in every take.

typescript
const cuts = splitSilenceCommon({ signals: [takeA, takeB, takeC], topDb: 55 });

Takes of unequal length need no padding: a signal shorter than the longest simply contributes nothing past its own end. Passing a single signal returns exactly what splitSilence would.

Frame / Pad / Length Helpers ​

typescript
function frameSignal(request: { samples: Float32Array; sampleRate: number; frameLength: number; hopLength: number }): Matrix2D  // rows = frameLength, cols = frames

function padCenter(request: { values: Float32Array; targetSize: number; padValue?: number }): Float32Array
function fixLength(request: { values: Float32Array; targetSize: number; padValue?: number }): Float32Array
function fixFrames(request: { frames: Int32Array | number[]; xMin?: number; xMax?: number; pad?: boolean }): Int32Array

frameSignal is librosa.util.frame; padCenter, fixLength, and fixFrames mirror the librosa.util helpers of the same names.

Peak Picking / Vector Normalize ​

typescript
function peakPick(request: {
  values: Float32Array;
  preMax: number;
  postMax: number;
  preAvg: number;
  postAvg: number;
  delta: number;
  wait: number;
}): Int32Array  // peak indices

function vectorNormalize(request: {
  values: Float32Array;
  norm?: 'max' | 'l1' | 'l2' | 'power',  // default 'max'
  threshold?: number,                     // default 0
}): Float32Array

peakPick is librosa.util.peak_pick (post-processing for 1-D signals such as onset envelopes); vectorNormalize is librosa.util.normalize. See librosa Compatibility for the peakPick window parameters and each norm.

PCEN (Per-Channel Energy Normalization) ​

typescript
function pcen(request: {
  values: Matrix2D;         // rows = bins, cols = frames
  sampleRate?: number;      // default 22050
  hopLength?: number;       // default 512
  timeConstant?: number;    // default 0.4
  gain?: number;            // default 0.98
  bias?: number;            // default 2.0
  power?: number;           // default 0.5
  eps?: number;             // default 1e-6
}): Matrix2D

pcen matches librosa.pcen. Input is a Matrix2D mel spectrogram (rows bins by cols frames, row-major); output uses the same layout.

Tonnetz / Tempogram / PLP ​

typescript
// Every one takes a request object; each Matrix2D has rows x cols = data.length
function tonnetz(request: { chromagram: Matrix2D }): Matrix2D     // [6 x frames]

function tempogram(request: {
  onsetEnvelope: Float32Array;
  sampleRate?: number;        // default 22050
  hopLength?: number;         // default 512
  winLength?: number;         // default 384
  mode?: 'autocorrelation' | 'cosine';  // default 'autocorrelation'
  center?: boolean;           // default true
  norm?: boolean;             // default true
}): Matrix2D

function fourierTempogram(request: {
  onsetEnvelope: Float32Array;
  sampleRate?: number;        // default 22050
  hopLength?: number;         // default 512
  winLength?: number;         // default 384
  center?: boolean;           // default true
}): Matrix2D

function cyclicTempogram(request: {
  onsetEnvelope: Float32Array;
  sampleRate: number;         // required
  hopLength?: number;         // default 512
  winLength?: number;         // default 384
  bpmMin?: number;            // default 60
  nBins?: number;             // default 60
}): Matrix2D

function tempogramRatio(request: {
  tempogram: Matrix2D;
  sampleRate?: number;        // default 22050
  hopLength?: number;         // default 512
  factors?: Float32Array | number[]; // default [0.5, 1, 2, 3, 4]
}): Float32Array

function plp(request: {
  onsetEnvelope: Float32Array;
  sampleRate?: number;        // default 22050
  hopLength?: number;         // default 512
  bpmMin?: number;            // default 60
  bpmMax?: number;            // default 200
  winLength?: number;         // default 384
}): Float32Array

For tempogram, mode: 'cosine' selects the window-local cosine-similarity variant. See librosa Compatibility for the librosa feature each helper maps to, and Realtime and Streaming for when to use each.

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 (a PitchClass, C = 0); natural major is 0b101010110101. scaleReferenceMidi is the tuning anchor (omit it for A4 = 69; 0 is MIDI note 0; the range is [0, 127]).

typescript
// Snap a (possibly fractional) MIDI number to the nearest enabled pitch class
function scaleQuantizeMidi(root: number, modeMask: number, midi: number, scaleReferenceMidi?: number): number
// Correction (quantized − input), in semitones
function scaleCorrectionSemitones(root: number, modeMask: number, midi: number, scaleReferenceMidi?: number): number
// Is pitchClass (0..11) enabled by modeMask relative to root?
function scalePitchClassEnabled(root: number, modeMask: number, pitchClass: number): boolean
// The mask of a mode, in that layout. mode is a church-mode name, the same set as KeyMode.
function scaleMaskForMode(root: PitchClass, mode: KeyMode): number
typescript
scaleMaskForMode(0, 'major');   // 0b101010110101
scaleMaskForMode(2, 'dorian');  // 0b11010101101, the same mask for any root

scaleMaskForMode takes the mode names detectKey reports, so a detected key becomes a correction target without a hand-written table; minor is the natural minor, an unknown name throws RangeError, and an ordinal throws TypeError. Pair scaleQuantizeMidi(...) with pitchCorrectToMidi(...) to retune a detected note to the nearest scale degree. To tune a whole recording to a detected or named key, see autoTune in Vocal Editing.

Unit Conversion ​

These functions are lightweight and fast.

typescript
// Hz <-> Mel (Slaney formula)
function hzToMel(hz: number): number
function melToHz(mel: number): number

// Hz <-> MIDI note number (A4 = 440 Hz = 69)
function hzToMidi(hz: number): number
function midiToHz(midi: number): number

// Hz <-> Note name
function hzToNote(hz: number): string      // "A4", "C#5"
function noteToHz(note: string): number

// Tuning (cents, as the analysis options take it) <-> reference pitch in Hz
function tuningToReferenceHz(tuningCents: number, a4Hz?: number): number   // a4Hz default 440
function referenceHzToTuning(referenceHz: number, a4Hz?: number): number

// Time <-> Frames (positional only)
function framesToTime(frames: number, sampleRate?: number, hopLength?: number): number
function timeToFrames(timeSec: number, sampleRate?: number, hopLength?: number): number

// Frames <-> Samples (librosa.frames_to_samples / samples_to_frames)
function framesToSamples(frames: number, hopLength?: number, nFft?: number): number
function samplesToFrames(samples: number, hopLength?: number, nFft?: number): number

// dB conversions (vectorised); each takes a request object { values, ... }
function powerToDb(request: { values: Float32Array; ref?: number; amin?: number; topDb?: number }): Float32Array
function amplitudeToDb(request: { values: Float32Array; ref?: number; amin?: number; topDb?: number }): Float32Array
function dbToPower(request: DbToPowerRequest): Float32Array
function dbToAmplitude(request: DbToAmplitudeRequest): Float32Array

noteToHz throws RangeError for a name that does not parse or whose octave is outside -1 to 9 (the octaves of the MIDI note range), and hzToNote for a frequency that is not finite and positive. The scalar conversions check their argument types: a value that is not a number throws TypeError.

The analysis options state tuning in cents (tuningCents), while transcription's referenceHz is in Hz. tuningToReferenceHz(tuningCents) is 440 * 2 ** (tuningCents / 1200), and referenceHzToTuning(referenceHz) is its inverse; pass a4Hz for a concert pitch other than 440.

typescript
referenceHzToTuning(442);      // 7.85 cents
tuningToReferenceHz(25);       // 446.4 Hz

Resampling ​

resample(samples, sampleRate, targetSampleRate) Medium ​

High-quality resampling using r8brain algorithm.

typescript
function resample(request: { samples: Float32Array; sampleRate: number; targetSampleRate: number }): Float32Array
function resample(samples: Float32Array, sampleRate: number, targetSampleRate: number): Float32Array

chordFunctions({ chords, key }) ​

Labels chords you already have with their Roman numeral and harmonic function in a key. Nothing is re-detected, so it costs nothing next to the detection that produced the chords. chords is detectChords(...)'s result or its chords array, or entries built by hand (only root and quality are read); key is { root, mode }, so detectKey(...)'s result goes in unchanged. mode is a name (KeyMode); an ordinal is a TypeError. Every mode other than minor reads the major scale.

typescript
function chordFunctions<T extends ChordFunctionsInput>(request: {
  chords: readonly T[] | { chords: readonly T[] };
  key: { root: PitchClass; mode: KeyMode };
}): FunctionalChord<T>[]
typescript
const key = detectKey(samples, sampleRate);
const detected = detectChords(samples, sampleRate);
const labelled = chordFunctions({ chords: detected, key });
console.log(labelled.map((c) => c.romanNumeral));  // e.g. ["I", "IV", "V", "I"]

An unrecognized mode name throws RangeError.

Key detection options ​

detectKey(...) and detectKeyCandidates(...) accept the same KeyDetectionOptions, tuningCents (number | 'auto', in cents) included. Omitted, tuningCents is measured from the audio; 0 reads the chroma at A440. The result and the rest of the call are documented under detectKey in the Analysis API.

OptionValuesDefault
modes'majorMinor', 'modal', 'all', or a list of mode names (['major', 'minor'])'majorMinor'
profilekrumhanslSchmuckler, temperley, shaath, faraldoEdmt, faraldoEdma, faraldoEdmm, bellmanBudgeomitted: the genre hint or the chroma chooses; a pinned profile outranks genreHint
genreHintauto, edm, electronic, dance, pop, classical, jazzauto
useHpssDetect on the harmonic component (HPSS, margin 3)false
loudnessWeightedWeight chroma frames by loudnessfalse
chromaHighPassHzHigh-pass cutoff before the chroma; 0 disables it80
nFftWindow length in samples at 22050 Hz, rescaled to the input rate; it only sets the window of the optional HPSS2048
hopLengthHop in samples of your buffer512