JavaScript/TypeScript Effects API
Audio effects and editing DSP in the libsonare JavaScript/TypeScript package. The room-acoustics calls live on Room Acoustics API.
Audio Effects
hpss(samples, sampleRate, options?) Heavy
Harmonic-Percussive Source Separation. Splits audio into tonal (vocals, synths) and transient (drums) components.
nFft must be an even integer of at least 4; mixed-radix FFT sizes are accepted. hopLength must be an integer in (0, nFft / 2] (default nFft / 4). Both median kernels must be positive odd integers at most 524287. The underlying STFT window and winLength must provide overlap-add coverage without gaps; these JavaScript helpers use the default window geometry. Invalid geometry is refused instead of returning periodic dropouts.
Performance
HPSS requires STFT (short-time Fourier transform) computation and median filtering. Processing time scales with audio duration.
function hpss(request: HpssRequest): HpssResult
function hpss(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<HpssRequest>,
): HpssResult
interface HpssRequest {
samples: Float32Array; // Mono input audio.
sampleRate: number; // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
kernelHarmonic?: number; // Horizontal median filter size, in STFT frames: a positive odd integer at most 524287. Default 31. The ceiling is 524288 and an even kernel is refused, so 524287 is the largest legal value.
kernelPercussive?: number; // Vertical median filter size, in STFT bins, under the same rule. Default 31.
nFft?: number; // FFT size in samples. Default 2048.
hopLength?: number; // Hop in samples. Default `nFft / 4`, rounded down.
hardMask?: boolean; // Threshold the masks into binary ones instead of the soft split. Default `false`.
withResidual?: boolean; // Also return `residual`, what neither component claimed. Default `false`.
}
interface HpssResult {
harmonic: Float32Array; // Harmonic component, the same length as the input.
percussive: Float32Array; // Percussive component, the same length as the input.
residual?: Float32Array; // What neither component claimed (input - harmonic - percussive), the same length as the input.
sampleRate: number; // Sample rate in Hz of both components.
}With withResidual: true, hpss also returns the residual component that is not classified as harmonic or percussive; the other options are unchanged.
const result = hpss({ samples, sampleRate, withResidual: true }); // result.residual is presentharmonic(samples, sampleRate) Heavy
Extract harmonic component from audio.
function harmonic(request: HarmonicRequest): Float32Array
function harmonic(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<HarmonicRequest>,
): Float32Arraypercussive(samples, sampleRate) Heavy
Extract percussive component from audio.
function percussive(request: PercussiveRequest): Float32Array
function percussive(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<PercussiveRequest>,
): Float32ArraytimeStretch(samples, sampleRate, options) Heavy
Time-stretch audio without changing pitch. speedRatio < 1.0 = slower, > 1.0 = faster. See Phase vocoder and time stretching.
Performance
Uses phase vocoder algorithm. Processing time increases with audio duration.
function timeStretch(request: TimeStretchRequest): Float32Array
function timeStretch(
samples: Float32Array,
sampleRate: number,
options: OptionsOf<TimeStretchRequest>,
): Float32Array
interface TimeStretchRequest {
samples: Float32Array; // Mono input audio.
sampleRate: number; // Sample rate in Hz. Required.
speedRatio: number; // Playback speed: `> 1` is faster and shorter (2 halves the duration), `< 1` is slower and longer (0.5 doubles it).
nFft?: number; // FFT size: an even integer in `[4, 2147483646]`. Default 2048.
hopLength?: number; // Hop in samples, in `(0, nFft / 2]`. Default `nFft / 4`, rounded down.
}pitchShift(samples, sampleRate, options) Heavy
Pitch-shift audio without changing duration. Measured in semitones (+12 = one octave up). See Phase vocoder and time stretching.
Performance
Combines time stretching and resampling. Processing time increases with audio duration.
function pitchShift(request: PitchShiftRequest): Float32Array
function pitchShift(
samples: Float32Array,
sampleRate: number,
options: OptionsOf<PitchShiftRequest>,
): Float32Array
interface PitchShiftRequest {
samples: Float32Array; // Mono input audio.
sampleRate: number; // Sample rate in Hz. Required.
pitchSemitones: number; // Shift in semitones: +12 is one octave up, -12 one octave down.
nFft?: number; // FFT size: an even integer in `[4, 2147483646]`. Default 2048.
hopLength?: number; // Hop in samples, in `(0, nFft / 2]`. Default `nFft / 4`, rounded down.
}Editing DSP
These functions change the signal itself rather than only analyzing it. They are also available as Audio instance methods, where the stored sampleRate is used automatically. Background: Pitch correction and Voice and formants. Each takes one request object; the positional form (samples, sampleRate, options) is shown where a function has one. The blocks are from the WASM package's type declarations, and Node declares the same fields.
function pitchCorrectToMidi(request: PitchCorrectToMidiRequest): Float32Array
function pitchCorrectToMidi(
samples: Float32Array,
sampleRate: number,
options: OptionsOf<PitchCorrectToMidiRequest>,
): Float32Array
interface PitchCorrectToMidiRequest {
samples: Float32Array; // Mono input audio.
sampleRate: number; // Sample rate in Hz. Required.
currentMidi: number; // MIDI note the audio currently sits on, in `[0, 127]`.
targetMidi: number; // MIDI note to move it to, in `[0, 127]`.
}
function pitchCorrectTimevarying(request: PitchCorrectTimevaryingRequest): Float32Array
function pitchCorrectTimevarying(
samples: Float32Array,
sampleRate: number,
options: PitchCorrectOptions,
): Float32Array
interface PitchCorrectTimevaryingRequest extends PitchCorrectOptions {
samples: Float32Array; // Mono input audio.
sampleRate: number; // Sample rate in Hz. Required.
}
interface PitchCorrectOptions {
f0Hz: Float32Array; // Per-frame measured F0 in Hz, one entry per analysis frame.
hopLength?: number; // F0 frame-center spacing in samples: frame `i` is centered at sample `i * hopLength`, and nearest-frame voicing switches halfway between centers. Default 512.
targetMode?: PitchTargetMode; // `'midi'` retunes toward `targetMidi`; `'scale'` snaps to the key. Default `'midi'`.
targetMidi?: number; // Fixed target note when `targetMode` is `'midi'`, in `[0, 127]`. Default 69 (A4).
scaleRoot?: number; // Scale root pitch class (0=C .. 11=B) when `targetMode` is `'scale'`. Default 0.
scaleModeMask?: number | KeyMode; // Scale degrees enabled: a 12-bit mask (bit `i` = semitone `i` above the root) or a mode name, as `scaleMaskForMode` resolves it. Default C major.
scaleReferenceMidi?: number; // Reference MIDI anchoring the scale grid. Default 69 (A4).
retuneAmount?: number; // Correction strength in `[0, 1]`; 1 = full snap, 0 = bypass. Default 1.
maxCorrectionSemitones?: number; // Hard clamp on per-frame correction magnitude (semitones). Default 12.
retuneSpeedMs?: number; // Retune IIR time constant (ms); larger = slower glide. Default 50.
vibratoThresholdCents?: number; // Corrections below this are bypassed to preserve vibrato (cents). Default 20.
voiced?: VoicedFlags; // Per-frame voiced flags (truthy = voiced); when supplied, these take precedence over `voicedProb`. Omit it to use `voicedProb`; with neither, all frames are treated as voiced.
voicedProb?: Float32Array; // Per-frame voicing probability in `[0, 1]`; used only when `voiced` is omitted, and ignored when flags are supplied.
}
type VoicedFlags =
| Int32Array
| Uint8Array
| Float32Array
| readonly number[]
| readonly boolean[];VoicedFlags is the accepted shape of PitchCorrectOptions.voiced. It covers what the analysis side hands back: PitchResult.voicedFlag is a boolean[], so a pitch track goes straight into pitch correction with no conversion step.
const pitch = pitchPyin(samples, sampleRate);
const tuned = pitchCorrectTimevarying({
samples,
sampleRate,
f0Hz: pitch.f0,
hopLength: 512,
targetMode: 'midi',
targetMidi: 69,
voiced: pitch.voicedFlag, // boolean[] accepted as-is
});voiced must be the same length as f0Hz; when it is omitted, voicedProb must also be the same length. A mismatch throws a RangeError (for example, 'pitchCorrectTimevarying: voiced must have the same length as f0Hz'), not a SonareError, so isSonareError does not catch it. Every frame treated as voiced must have an f0Hz that is finite, strictly positive, and no higher than the Nyquist frequency (sampleRate / 2); violating this rejects the call. An unvoiced frame may use NaN (a finite value from 0 through Nyquist is also accepted), but NaN is never valid for a voiced frame.
A track with an unvoiced (NaN) frame needs a voicing source: with neither voiced nor voicedProb every frame is treated as voiced, and a NaN in a voiced frame is refused. Pass voiced (for example { voiced: pitch.voicedFlag }).
voicedProb decides voicing, and nothing else
voicedProb exists for one purpose: to derive a per-frame voiced/unvoiced decision when voiced is not supplied. When voiced is supplied, voicedProb is ignored entirely — passing both is a no-op, which is why the example above passes only the flags.
In particular it does not scale the per-frame correction amount. If you were passing voicedProb expecting a soft, probability-weighted retune, you are not getting one, and the correction you hear will be stronger in the low register than that reading predicts — voicedProb rises with F0, so the frames it would have attenuated most are the low ones. Use retuneAmount and vibratoThresholdCents to soften a correction.
function noteStretch(request: NoteStretchRequest): Float32Array
function noteStretch(
samples: Float32Array,
sampleRate: number,
options: NoteStretchOptions,
): Float32Array
function noteMove(request: NoteMoveRequest): Float32Array
function noteMove(
samples: Float32Array,
sampleRate: number,
options: NoteMoveOptions,
): Float32Array
interface NoteStretchOptions {
onsetSample?: number; // Note onset position in samples (selects the region). Default 0. Not with `onsetSec`.
onsetSec?: number; // Note onset in seconds, rounded to the nearest sample. Not with `onsetSample`.
offsetSample?: number; // Note offset position in samples (selects the region). Defaults to the input length. Not with `offsetSec`.
offsetSec?: number; // Note offset in seconds, rounded to the nearest sample. Not with `offsetSample`.
stretchRatio: number; // Duration ratio of the note (0.5 = half duration, 2.0 = double duration).
}
interface NoteMoveOptions {
onsetSample?: number; // First sample of the note to move. Default 0. Not with `onsetSec`.
onsetSec?: number; // First second of the note to move, rounded to the nearest sample. Not with `onsetSample`.
offsetSample?: number; // Defaults to the input length. Not with `offsetSec`.
offsetSec?: number; // Last second of the note to move, rounded to the nearest sample. Not with `offsetSample`.
targetOnsetSample?: number; // Sample the note's onset moves to. Required unless given as `targetOnsetSec`.
targetOnsetSec?: number; // Second the note's onset moves to, rounded to the nearest sample. Not with `targetOnsetSample`.
}Audio.noteStretch(options) and Audio.noteMove(options) are the equivalent instance methods on an Audio wrapper (sample rate taken from the instance). Negative sample positions (onsetSample, offsetSample, targetOnsetSample) are refused with a RangeError naming the field, and each position can be given in seconds instead (onsetSec, offsetSec, targetOnsetSec), never both spellings of one bound.
function spectralEdit(request: SpectralEditRequest): Float32Array
function spectralEdit(
samples: Float32Array,
sampleRate: number,
options: SpectralEditOptions,
): Float32Array
interface SpectralEditOptions {
ops: readonly SpectralRegionOp[]; // Region edit ops applied in array order; an empty array returns a copy of the input.
nFft?: number; // FFT size; a power of two in `[4, 262144]`. Omit for 2048; 0 is refused.
hopLength?: number; // Hop length; `0 < hopLength <= nFft / 2`. Omit for a quarter of `nFft`; 0 is refused.
window?: WindowType; // Analysis + synthesis window. Default 'hann'.
healRadiusFrames?: number; // Neighbour frames each side used by `'heal'`, at least 1. Omit for 2; 0 is refused.
}
interface SpectralRegionOp {
startSample?: number; // Region time start in input samples; past the end reads as the end, a negative value is refused. Default 0. Not with `startSec`.
startSec?: number; // Region time start in seconds, rounded to the nearest sample. Not with `startSample`.
endSample?: number; // Region time end (exclusive) in input samples. Omit for the end of the signal; a negative value is refused. Not with `endSec`.
endSec?: number; // Region time end in seconds, rounded to the nearest sample. Not with `endSample`.
lowHz?: number; // Region frequency low edge in Hz; clamped to [0, nyquist]. Default 0.
highHz?: number; // Region frequency high edge in Hz, finite and greater than 0; at or above Nyquist reads as Nyquist. Omit for Nyquist.
gainDb?: number; // Linear gain in dB for 'gain'/'attenuate'; ignored by 'mute'/'heal'. Default 0.
mode?: SpectralEditMode; // Edit mode. Default 'gain'.
}
function voiceChange(request: VoiceChangeRequest): Float32Array
function voiceChange(
samples: Float32Array,
sampleRate: number,
options?: VoiceChangeOptions,
): Float32Array
interface VoiceChangeOptions {
pitchSemitones?: number; // Pitch shift in semitones (negative = down). Default 0.
formantFactor?: number; // Formant scale factor (>1 brightens, <1 darkens). Default 1.
formantMode?: FormantMode; // How `formantFactor` relates to the pitch shift. Default `'relative'`.
}CLI equivalents:
sonare pitch-correct vocal.wav --current-midi 68.7 --target-midi 69 -o corrected.wav
sonare note-stretch take.wav --onset-sample 12000 --offset-sample 24000 --ratio 1.25 -o held.wav
sonare voice-change vocal.wav --pitch-semitones 3 --formant-factor 1.05 -o voice.wavformantMode sets what formantFactor is measured against. In 'relative' (the default) the factor is a warp applied after the pitch shift, so the formants follow the pitch by formantFactor * 2^(pitchSemitones / 12). In 'absolute' the factor is the formant shift relative to the input whatever the pitch shift (1 keeps the formants where they were). A relative request whose formantFactor is outside [0.55, 1.65] throws a RangeError. Absolute mode limits how far the formants can be held against the pitch shift, and a request outside that limit throws a RangeError; it is never clamped. Any other mode string is a RangeError. The CLI takes the same choice as --formant-mode relative|absolute.
// Up four semitones, formants left where they were
const out = voiceChange(vocal, 48000, { pitchSemitones: 4, formantFactor: 1, formantMode: 'absolute' });spectralEdit takes its region list as ops inside the options, and requires nFft to be a power of two in [4, 262144]; an explicit 0 for nFft, hopLength or healRadiusFrames is refused rather than read as the default (RangeError: spectralEdit: nFft must be a power of two in [4, 262144]), and a negative region sample position is a RangeError. See Spectral Editing for region examples and option notes.
pitchCorrectTimevarying(...) is the scale-snap pitch correction path; see Editing DSP for the scale masks, targetMode, and retune-feel options in full.
normalize(samples, sampleRate, options?)
Normalize audio to the requested target level. mode is 'peak' by default; use 'rms' to target RMS level instead.
function normalize(request: NormalizeRequest): Float32Array
function normalize(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<NormalizeRequest>,
): Float32Array
interface NormalizeRequest {
samples: Float32Array; // Mono input samples.
sampleRate: number; // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
targetDb?: number; // Finite target level at or below 0 dBFS. Defaults to 0 for `mode: 'peak'` and -20 for `mode: 'rms'`.
mode?: NormalizeMode; // Normalization statistic. Default `'peak'`.
}normalizeStereo(request)
Normalize a stereo pair with one shared gain, so the stereo image survives.
function normalizeStereo(request: NormalizeStereoRequest): NormalizeStereoResult // request form only
interface NormalizeStereoRequest {
left: Float32Array; // Left channel samples.
right: Float32Array; // Right channel samples.
sampleRate: number; // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
targetDb?: number; // Finite target level at or below 0 dBFS. Defaults to 0 for `mode: 'peak'` and -20 for `mode: 'rms'`.
mode?: NormalizeMode; // Normalization statistic. Default `'peak'`.
}
interface NormalizeStereoResult {
left: Float32Array; // Normalized left channel.
right: Float32Array; // Normalized right channel.
appliedGainDb: number; // One figure rather than a pair: the gain is one decision shared by both channels. An all-silent pair is refused.
}The level is read from the pair and the resulting gain goes to both channels unchanged. That is the whole point: normalizing each channel to its own target would change the balance rather than the level, turning a deliberate pan into a centered mix. Because the decision is shared, appliedGainDb is a single figure and not a per-channel pair. In 'peak' mode the louder channel reaches targetDb and the quieter one keeps its distance below it. In 'rms' mode the quantity driven to targetDb is the RMS over both channels' samples together — the quadratic mean of the per-channel figures, not their average — with no clipping of the output.
Choose an RMS target with peak headroom
Both normalize and normalizeStereo default targetDb to 0 for mode: 'peak' and -20 for mode: 'rms'. An explicit RMS target of 0 dBFS can drive peaks beyond full scale; the floating-point output retains those peaks. Leave the target omitted or choose an explicit RMS target with enough headroom for the signal's peaks.
Unequal channel lengths and an all-silent pair both raise RangeError.
trim(samples, sampleRate, options?)
Trim silence from beginning and end of audio.
function trim(request: TrimRequest): Float32Array
function trim(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<TrimRequest>,
): Float32Array
interface TrimRequest {
samples: Float32Array; // Mono audio samples.
sampleRate: number; // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
thresholdDb?: number; // Silence threshold in dBFS. Default -60.
frameLength?: number; // Analysis frame in samples. Default 2048.
hopLength?: number; // Hop in samples. Default 512.
}
function trimSilence(request: TrimSilenceRequest): TrimResult
function trimSilence(
samples: Float32Array,
sampleRate: number,
options?: OptionsOf<TrimSilenceRequest>,
): TrimResult
interface TrimSilenceRequest {
samples: Float32Array; // Mono audio samples.
sampleRate: number; // Sample rate of `samples` in Hz.
topDb?: number; // Threshold below the peak, in dB. Default 60.
frameLength?: number; // Analysis frame in samples. Default 2048.
hopLength?: number; // Hop in samples. Default 512.
}
interface TrimResult {
audio: Float32Array; // The trimmed samples.
startSample: number; // Index in the input of the first kept sample.
endSample: number; // Index in the input where the kept range ends (exclusive).
}This is the simple Audio-level threshold trim. For librosa-compatible frame/RMS silence detection that also returns the original start/end sample range, use trimSilence(...) above.