Pitch Correction: Snap Vocals to a Note or Key
Pitch correction moves a recorded note toward a target pitch without changing how long it lasts. libsonare offers four routes, from one fixed interval on a held note to a whole recording snapped to a detected key. They work on decoded mono samples, so they suit simple vocal correction rather than a full pitch editor.
| Goal | Call | You supply |
|---|---|---|
| Move a held note from one MIDI note to another | pitchCorrectToMidi | The note it has now and the note you want |
| Follow a changing pitch toward one note | pitchCorrectTimevarying with targetMode: 'midi' | A per-frame pitch contour |
| Snap a line to a scale (automatic pitch correction) | pitchCorrectTimevarying with targetMode: 'scale' | A contour, a root and a scale |
| Tune a whole recording to its key | autoTune | Only the samples, or a named key |
Pitches are MIDI note numbers and semitones; Editing Basics and the units table cover the conversions. To move the whole clip by a fixed interval, use pitchShift on Change Tempo Without Changing Pitch instead. Concepts behind the options, including the two resynthesis engines, are on the pitch correction glossary page.
How pitchCorrectToMidi(...) works
pitchCorrectToMidi(...) takes two MIDI note numbers: the pitch the audio currently has, and the pitch you want it to move toward. It does not detect the current pitch by itself. The caller provides currentMidi / current_midi.
The usual workflow is:
- Estimate the current pitch with
pitchYin(...)orpitchPyin(...)(pYIN is a probabilistic variant of the YIN pitch tracker that also reports which frames are voiced), or your own detector. - Pass the measured pitch as
currentMidi. - Pass the target note as
targetMidi.
import { init, pitchCorrectToMidi } from '@libraz/libsonare';
await init();
const currentMidi = 68.7; // slightly below A4
const targetMidi = 69; // A4
const tuned = pitchCorrectToMidi({ samples: vocal, sampleRate, currentMidi, targetMidi });import { pitchCorrectToMidi } from '@libraz/libsonare-native';
const tuned = pitchCorrectToMidi({ samples: vocal, sampleRate, currentMidi: 68.7, targetMidi: 69 });import libsonare as sonare
tuned = sonare.pitch_correct_to_midi(vocal, sample_rate, current_midi=68.7, target_midi=69)sonare pitch-correct vocal.wav --current-midi 68.7 --target-midi 69 -o tuned.wavTime-varying pitch correction
F0, frames, and "voiced"
F0 is the fundamental frequency — the pitch — measured in Hz. A pitch detector reports one F0 per short time slice (a frame, here one hopLength of samples), giving an F0 contour that traces how the pitch moves. A frame is voiced when the singer is actually producing pitched sound (a sung vowel) rather than a breath or silence; only voiced frames are worth retuning.
pitchCorrectToMidi(...) applies the requested transpose immediately and preserves the input length. It does not follow a changing pitch contour.
Use pitchCorrectTimevarying(...) when correction should change from frame to frame. It follows a caller-supplied per-frame F0 contour and retunes each voiced frame toward targetMidi.
import { init, pitchPyin, pitchCorrectTimevarying } from '@libraz/libsonare';
await init();
const hopLength = 512;
// 1. Measure a per-frame F0 contour (any detector that emits one F0 per hop).
const pitch = pitchPyin({ samples: vocal, sampleRate, hopLength });
// 2. Retune every voiced frame toward A3 (MIDI 57) while keeping the contour.
const tuned = pitchCorrectTimevarying({
samples: vocal,
sampleRate,
f0Hz: pitch.f0, // Float32Array, one F0 (Hz) per analysis frame
hopLength, // frame i covers sample i * hopLength
targetMode: 'midi',
targetMidi: 57, // target MIDI note
voiced: pitch.voicedFlag, // optional: only retune voiced frames
});voiced and voicedProb are optional. Omit both to treat every frame as voiced. When only voicedProb is given, a frame counts as voiced when its probability is at least 0.5; when voiced is given too, voiced decides and voicedProb is ignored. Use the same hopLength that produced the F0 contour, so frame i lines up with sample i * hopLength.
voiced is typed VoicedFlags — Int32Array, Uint8Array, Float32Array, readonly number[], or readonly boolean[]. Each entry is read as a flag, not a magnitude: any truthy value means voiced. That is why pitch.voicedFlag, which pitchPyin returns as a boolean[], goes straight in with no conversion step.
voiced must match the length of f0Hz; if you leave voiced out, voicedProb must. A mismatch throws a RangeError rather than a SonareError, so an isSonareError guard will not catch it.
A voiced frame must have a finite, positive f0Hz no higher than Nyquist (sampleRate / 2); zero, negative, or non-finite voiced F0 is rejected. An unvoiced frame may carry NaN or a finite F0 between zero and Nyquist. Pass voiced flags from the pitch analysis when its unvoiced frames contain NaN.
Contour-following correction defaults to ±12 semitones
pitchCorrectTimevarying(...) uses the corrector's default ±12-semitone bound for each measured frame. pitchCorrectToMidi(...) applies the caller-stated targetMidi - currentMidi interval in full after validating the MIDI endpoints, so pitchCorrectToMidi({ samples: vocal, sampleRate, currentMidi: 48, targetMidi: 72 }) moves by +24 semitones.
When you need a wider contour correction, call pitchCorrectTimevarying(...) with an explicit maxCorrectionSemitones. For a plain transpose, use pitchShift(...).
Constant vs contour-following correction
Use pitchCorrectToMidi(...) for a steady held note where one transpose is enough. Reach for pitchCorrectTimevarying(...) when the take has vibrato, slides, or drift you want to preserve while nudging it onto pitch.
Scale-snap correction
The two calls above pull toward a single note. When a whole vocal line should follow a key, with each note snapped to the nearest tone of, say, C major, use pitchCorrectTimevarying(...). It takes the same per-frame F0 contour but reads its target and correction feel from an options object. targetMode: 'scale' is automatic pitch correction in the usual sense: every voiced frame is pulled to the closest scale tone rather than one fixed pitch.
import { init, pitchPyin, pitchCorrectTimevarying } from '@libraz/libsonare';
await init();
const hopLength = 256;
const pitch = pitchPyin({ samples: vocal, sampleRate, hopLength });
// Snap every voiced frame to C major at 80% strength.
const tuned = pitchCorrectTimevarying({
samples: vocal,
f0Hz: pitch.f0,
sampleRate,
hopLength,
targetMode: 'scale',
scaleRoot: 0, // 0 = C .. 11 = B
scaleModeMask: 0xab5, // 12-bit degree mask: C major = {0,2,4,5,7,9,11}
retuneAmount: 0.8, // 0 = bypass, 1 = full snap
retuneSpeedMs: 15, // larger = slower glide onto pitch
maxCorrectionSemitones: 2, // clamp any single frame's jump (default 12)
voiced: pitch.voicedFlag, // the boolean[] from pitchPyin, passed as-is
});import libsonare as sonare
hop_length = 256
pitch = sonare.pitch_pyin(vocal, sample_rate, hop_length=hop_length)
tuned = sonare.pitch_correct_timevarying(
vocal,
sample_rate,
pitch.f0,
hop_length,
target_mode="scale",
scale_root=0,
scale_mode_mask=0xAB5,
retune_amount=0.8,
retune_speed_ms=15,
max_correction_semitones=2,
voiced=pitch.voiced_flag,
)# The CLI measures the pYIN contour itself
sonare pitch-correct-timevarying vocal.wav --mode scale --scale-root 0 --scale-mode-mask 2741 --retune-amount 0.8 -o tuned.wavNode takes the same calls as the browser. Python passes the options as keyword-only arguments instead of an options dictionary. The CLI covers pitchCorrectTimevarying, but has no command for autoTune or spectralEdit.
| Option | Python | CLI flag | Range | Default | Effect |
|---|---|---|---|---|---|
targetMode | target_mode | --mode | 'midi', 'scale' | 'midi' | 'midi' retunes toward targetMidi; 'scale' snaps to the key |
targetMidi | target_midi | --target-midi | [0, 127] | 69 | Fixed target note in 'midi' mode |
scaleRoot | scale_root | --scale-root | 0 (C) to 11 (B) | 0 | Root pitch class of the scale |
scaleModeMask | scale_mode_mask | --scale-mode-mask | 12-bit mask or a mode name | C major (0xab5) | Enabled scale degrees; bit i is the semitone i above scaleRoot |
scaleReferenceMidi | scale_reference_midi | --reference-midi | finite | 69 | Anchors the scale grid; every degree is measured from this note |
retuneAmount | retune_amount | --retune-amount | [0, 1] | 1 | 0 bypasses, 1 snaps fully; lower values leave a natural wobble |
retuneSpeedMs | retune_speed_ms | --retune-speed-ms | >= 0 | 50 | Retune time constant: after this many ms the correction has covered about 63% of the gap, so larger glides onto pitch more slowly |
vibratoThresholdCents | vibrato_threshold_cents | --vibrato-threshold-cents | >= 0 | 20 | Frames this close to the target count as in tune and are left alone |
maxCorrectionSemitones | max_correction_semitones | --max-correction-semitones | >= 0 | 12 | Hard clamp on one frame's jump |
voiced / voicedProb | voiced / voiced_prob | (measured by the CLI) | flags / [0, 1] | all frames voiced | Which frames to retune; voiced wins over voicedProb |
A cent is 1/100 of a semitone, so the default vibratoThresholdCents of 20 leaves any frame within a fifth of a semitone of its target alone: it is already in tune. Sung vibrato swings much wider than that, typically ±50 to ±100 cents at 5 to 7 Hz, so the threshold does not protect it. What keeps vibrato alive is a slower retuneSpeedMs (or a retuneAmount below 1): the smoothed correction then follows the note's average pitch rather than every swing, while a very short time constant chases each swing and flattens it. retuneAmount: 1 with a short retuneSpeedMs is the hard, robotic effect; maxCorrectionSemitones bounds an octave-off detector glitch on one frame instead of yanking that frame a full octave, so lower it when the detector is noisy.
C natural minor {0,2,3,5,7,8,10} is 0x5ad. With targetMode: 'midi' the function retunes toward the fixed targetMidi instead of the scale. The pitch correction glossary page explains the options conceptually.
Tune a whole recording to a key: autoTune(...)
The functions above need an F0 contour you measured yourself. autoTune(...) runs the whole offline chain on a monophonic recording. It analyzes with a 2048-sample frame at 22.05 kHz, held as a duration (about 93 ms at any sample rate), and a 512-sample hop. The output has the input's length; unvoiced stretches and notes the corrector cannot repitch pass through unchanged.
import { autoTune, init } from '@libraz/libsonare';
await init();
// Detect the key, then tune toward it.
const { samples: tuned, key } = autoTune({ samples: vocal, sampleRate, key: 'detect', retuneAmount: 0.8 });
console.log(key.name, key.confidence); // the key actually used
// Or name the key: confidence is 1, and no detection runs.
const inD = autoTune({ samples: vocal, sampleRate, key: { root: 2, mode: 'dorian' } });import libsonare as sonare
# Detect the key, then tune toward it.
result = sonare.auto_tune(vocal, sample_rate, key="detect", retune_amount=0.8)
print(result.key.name, result.key.confidence) # the key actually used
# Or name the key.
in_d = sonare.auto_tune(vocal, sample_rate, key=(2, "dorian"))key is 'detect' (the default) or { root, mode }, where root is a pitch class (0 = C .. 11 = B) and mode is a name such as 'major', 'minor', 'dorian'. The result is { samples, key }; key.mode is a name, as detectKey reports it, and detection reads the chroma at concert A440. retuneAmount (default 1), retuneSpeedMs, vibratoThresholdCents, maxCorrectionSemitones and scaleReferenceMidi mean what they do in pitchCorrectTimevarying(...). Python takes the key as a string, a Key, a mapping, or a (root, mode) tuple and returns an AutoTuneResult with samples and key.
To snap a contour you measured yourself, build the mask with scaleMaskForMode(root, mode) and pass it as scaleModeMask. It returns the 12-bit mask of a church mode (a scale such as major, dorian or minor; scaleMaskForMode(0, 'major') is 0b101010110101), and pitchCorrectTimevarying(...) also accepts the mode name directly as scaleModeMask.
For per-note corrections against a reference melody, see Note Editing in Audio. For a vocal session that keeps every note editable, see Vocal Editing.
Related
- Change Tempo Without Changing Pitch — the whole-clip pitch shift and the formant controls
- Editing DSP — the full function table and practical limits
- Pitch Correction — what the options do, conceptually