JavaScript/TypeScript Pitch and Notes API
Pitch tracking and note-level analysis of the libsonare JavaScript/TypeScript package. They take the same request-object conventions as Feature Extraction.
Pitch Detection Medium
function pitchYin(request: PitchYinRequest): PitchResult
function pitchYin(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<PitchYinRequest>,
): PitchResult
function pitchPyin(request: PitchPyinRequest): PitchResult
function pitchPyin(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<PitchPyinRequest>,
): PitchResult
interface PitchYinRequest {
samples: Float32Array; // Mono audio samples.
sampleRate: number; // Sample rate of `samples` in Hz.
frameLength?: number; // Frame length in samples. Default 2048.
hopLength?: number; // Hop in samples. Default 512.
f0MinHz?: number; // Lowest pitch searched, in Hz. Default 65.
f0MaxHz?: number; // Highest pitch searched, in Hz. Default 2093.
threshold?: number; // YIN threshold. Default 0.1.
}
interface PitchPyinRequest {
samples: Float32Array; // Mono audio samples.
sampleRate: number; // Sample rate of `samples` in Hz.
frameLength?: number; // Frame length in samples. Default 2048.
hopLength?: number; // Hop in samples. Default 512.
f0MinHz?: number; // Lowest pitch searched, in Hz. Default 65.
f0MaxHz?: number; // Highest pitch searched, in Hz. Default 2093.
threshold?: number; // YIN threshold. Default 0.1.
fillNa?: boolean; // Return 0 for unvoiced f0 frames instead of NaN. Default `false`.
}
interface PitchResult {
f0: Float32Array; // Per-frame fundamental frequency in Hz; unvoiced frames are NaN.
// pYIN's per-frame voiced **observation mass**, exactly as librosa returns it: the summed probability of the frame's voiced pitch hypotheses.
//
// This is NOT a signal-quality confidence and NOT a correction weight. The mass depends on how many periods of the pitch fit inside `frameLength`, because the CMNDF troughs of a long period measured over a short frame are shallower. For a fixed `frameLength` it therefore rises with F0 even when the signal is unchanged: a steady three-harmonic tone at 2048 samples / 48 kHz averages well under 0.1 at C2 and about 0.5 at C5, with every frame flagged voiced throughout.
//
// Use voicedFlag for any voicing decision. In particular, thresholding this value at a fixed 0.5 (`noteSegments`' default) drops entire low registers.
voicedProb: Float32Array;
voicedFlag: boolean[]; // Per-frame voicing decision from the Viterbi path — the voicing oracle.
medianF0?: number; // Median F0 in Hz over the voiced frames. Absent when no frame is voiced.
meanF0?: number; // Mean F0 in Hz over the voiced frames. Absent when no frame is voiced.
}YIN returns a finite estimate for every frame, including frames marked unvoiced by voicedFlag. pYIN keeps NaN for unvoiced frames by default; set fillNa: true when a downstream numeric pipeline should use 0 instead. Background: Melody and pitch.
Notes and struck sounds
These four sit between analysis and editing: each measures something the audio does not state, and hands back an object a host edits and renders. Note Editing covers the editing workflow around them.
analyzePolyphonic(request) Heavy
function analyzePolyphonic(request: AnalyzePolyphonicRequest): PolyphonicAnalysis
function analyzePolyphonic(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<AnalyzePolyphonicRequest>,
): PolyphonicAnalysis
interface AnalyzePolyphonicRequest extends PolyphonicAnalysisOptions {
samples: Float32Array; // Source audio; must be non-empty.
sampleRate: number; // Sample rate in Hz. Required: every duration in the chain — the ridge minimum, the note minimum, the per-frame windows — is converted to samples with this rate, so a wrong value silently analyses differently.
}Separates the notes of a chord so one of them can be edited and the rest left alone. It returns a handle, not a result: the analysis owns the source's complex spectrogram plus the bins each note claimed, which is the input again plus the claims, and keeping it is what makes re-rendering an edit free.
destroy() it as soon as you are done. Using it afterwards throws InvalidState rather than reaching a freed object. What crosses into JavaScript is only what a host acts on — the notes, each note's pending edit, the per-frame voice count, and per note a pitch, a level and a salience curve. The spectrogram, the masks and the per-bin weights never do, and no method reports a per-bin figure.
sampleRate is required rather than defaulted: every duration in the chain is converted to samples with it, so a wrong value analyzes differently without failing.
decomposeNotePitch(request)
function decomposeNotePitch(request: DecomposeNotePitchRequest): PitchDecompositionResult
interface DecomposeNotePitchRequest {
f0Hz: Float32Array; // The note's slice of the F0 track — `f0Hz.subarray(frameStart, frameEnd)`. Positive finite values carry pitch; other values carry no measurement.
voiced?: VoicedFlags; // Per-frame voiced flags matching `f0Hz`; false suppresses a candidate and true cannot make an unusable F0 valid.
frameRate: number; // F0 frames per second.
medianHz: number; // The note's `medianHz`. A note with no pitch is spelled 0, so a negative value is rejected rather than read as a second way of saying that.
vibratoCutoffHz?: number; // Where drift ends and vibrato begins, in Hz. Default 3 Hz.
}
interface PitchDecompositionResult {
centerHz: number; // The note's steady pitch in Hz. 0 when the note carries no usable pitch, and then both curves are empty.
driftCents: Float32Array; // Slow deviation from `centerHz` in cents, one entry per frame.
vibratoCents: Float32Array; // Fast deviation in cents, over the same frames.
}Splits one note's pitch curve into the three things it carries at once: the center that was aimed at, the slow wander around it, and the periodic oscillation on top. Editing any one of them needs them separated first.
vibratoCutoffHz is the only thing deciding where drift ends and vibrato begins. Hand the same cutoff to renderNotes, or it edits a curve nobody was shown.
Pass the note's original f0Hz track as a Float32Array and an optional voiced flag array with the same length. A false flag suppresses that frame even when its F0 is positive; true does not make a non-positive, non-finite, or otherwise unusable F0 valid. frameRate is required with f0Hz, and so is medianHz (the note's medianHz; a note with no pitch is spelled 0). Use the same track, flags, frame rate, and cutoff when rendering a curve edit; ordinary note edits do not need F0 metadata.
Frames whose F0 is unusable carry no measurement, so the curve is held at the nearest usable neighbor across them; both curves therefore have an entry everywhere, and a host marking the held ones checks f0Hz together with the supplied voiced flags when present. A note with no usable pitch comes back as a zero centerHz and two empty curves — that is a measurement that came up empty, not a bad argument.
extractPercussiveEvents(request) and renderPercussiveEvents(request)
function extractPercussiveEvents(request: ExtractPercussiveEventsRequest): PercussiveEvent[]
function extractPercussiveEvents(
samples: Float32Array | readonly number[],
sampleRate: number,
options?: OptionsOf<ExtractPercussiveEventsRequest>,
): PercussiveEvent[]
function renderPercussiveEvents(request: RenderPercussiveEventsRequest): Float32Array
function renderPercussiveEvents(
samples: Float32Array | readonly number[],
sampleRate: number,
options: OptionsOf<RenderPercussiveEventsRequest>,
): Float32Array
interface ExtractPercussiveEventsRequest extends PercussiveSeparationOptions {
samples: Float32Array | readonly number[]; // Source audio; a plain number array is copied to a `Float32Array` first.
sampleRate: number; // Sample rate in Hz. Required: `maxEventMs` is converted to samples with this rate, so a wrong/omitted value caps the spans differently.
onsetWait?: number; // Minimum frames between consecutive onsets, a positive whole number. Default 1; an explicit 0 or a negative wait is refused, and a fractional wait is refused rather than truncated.
onsetDelta?: number; // Offset added to the detector's adaptive threshold; raising it finds fewer, stronger hits and lowering it finds more. Default 0.06. An explicit 0 is refused because the native configuration would read it as the default; a negative one is accepted and puts the threshold below the default.
maxEventMs?: number; // Caps a span that no onset follows. It binds at the end of a phrase and at the end of the track; anywhere else the next onset closes the span first. Default 500 ms; an explicit 0 is refused.
minPercussiveRatio?: number; // Drops an event whose `percussiveRatio` falls below this; must be in `[0, 1]`. 0 is both the default and the meaningful "keep everything". Raising it is useful on material that is mostly drums and wrong on a dense mix, where it also drops real hits sitting over a loud sustain.
}
interface RenderPercussiveEventsRequest extends PercussiveSeparationOptions {
samples: Float32Array | readonly number[]; // Source audio; a plain number array is copied to a `Float32Array` first.
sampleRate: number; // Sample rate in Hz. Required: `fadeMs` is converted to samples with this rate, so a wrong/omitted value changes the fade length.
events: readonly PercussiveEventInput[]; // The events to render, with their edits. Source spans must not overlap.
fadeMs?: number; // Fade-out at the tail of each lifted span. Default 5 ms; an explicit 0 is refused rather than read as that default — and a hard cut is not a thing to want anyway, because what the fade shapes is the signal being subtracted, so squaring it off leaves a step. There is deliberately no matching fade-in: a span opens in front of its transient, where the percussive component is near-silent, so cutting square there costs nothing and keeps a muted hit's attack from surviving inside a fade.
}
interface PercussiveSeparationOptions {
nFft?: number; // FFT size and hop the separation and the onset detector share. They cannot be set apart: an event measured on one framing and lifted out on another is not the same signal. Default 2048 and a quarter of `nFft`. The pair must overlap-add — `nFft` even and at least 2, `hopLength` no more than half of it — because the separation inverts an STFT. An explicit 0 in any separation field is refused; leave the field out for its default.
hopLength?: number; // Hop length in samples. Default a quarter of `nFft`.
hpssKernelHarmonic?: number; // Median filter lengths the separation runs, along time and along frequency. A longer harmonic kernel calls more of a sustained sound harmonic. Default 31; any other value must be odd and positive, so an even one is rejected rather than rounded. 1 is legal and degenerate rather than an error: a length-1 median is the identity, so both components come back as the source.
hpssKernelPercussive?: number; // Vertical median filter length, under the same rule. Default 31.
}
interface PercussiveEventInput {
onsetSample?: number; // First sample of the span. Give this or `onsetSec`.
onsetSec?: number; // First second of the span, rounded to the nearest sample. Not with `onsetSample`.
offsetSample?: number; // One past the last sample of the span. Give this or `offsetSec`.
offsetSec?: number; // End of the span in seconds, rounded to the nearest sample. Not with `offsetSample`.
edit?: PercussiveEventEditInput; // Omit for the identity edit.
}
interface PercussiveEvent {
onsetSample: number; // First sample of the span, backtracked to in front of the transient.
offsetSample: number; // One past the last sample of the span; the next onset, or the cap.
strength: number; // Detector strength at the onset, on the onset envelope's own scale. It orders events against each other and carries no absolute meaning.
peakAmplitude: number; // Peak absolute sample of the percussive component over the span, linear. Measured on the signal `gainDb` scales rather than on the source.
// Share of the span's energy the separation assigned to percussion, in `[0, 1]`; absent when the span is silent.
//
// It describes the span rather than the onset that opened it. An isolated hit sits near 1, but a real hit over a loud sustain sits near 0, because the sustain owns the span's energy. So it separates a hit from a note attack only where nothing is sustaining through both, and it is not a test for whether a hit is there.
percussiveRatio?: number;
edit: PercussiveEventEdit; // This event's pending edit; the identity as returned.
}A pair. The first locates struck sounds in audio alone — each event is a span in source samples, its detector strength, the percussive peak over the span, the share of the span's energy the separation called percussive, and an identity edit. Edit the events, hand them to the second, and get the audio back. The source is never mutated, and a set whose edits are all identity renders back to the input.
Both take the same separation options, and both need sampleRate for the same reason: it converts maxEventMs and fadeMs into samples.
Two defaults are worth knowing. minPercussiveRatio defaults to 0, which means keep everything; raising it helps on material that is mostly drums and hurts on a dense mix, where it also drops real hits sitting over a loud sustain. fadeMs defaults to 5 ms and shapes the signal being subtracted, so there is no way to ask for a hard cut — squaring it off would leave a step. There is deliberately no matching fade-in: a span opens in front of its transient where the percussive component is near-silent.
The separation's median kernels must be odd and positive; an even one is rejected rather than rounded. 1 is legal and degenerate — a length-1 median is the identity, so both components come back as the source.