Skip to content

Change Tempo Without Changing Pitch ​

To change the tempo of decoded audio without changing its pitch, call timeStretch (time_stretch in Python) with a speedRatio. A ratio of 0.8 plays at 80% speed and makes the clip 1.25 times as long, at the same pitch; 1.25 plays faster and shorter. A media element's preservesPitch covers an <audio> element's playback rate. timeStretch returns new samples instead, which Web Audio can play, loop, edit or export.

js
import { init, timeStretch } from '@libraz/libsonare';

await init();

/** Returns a copy of `buffer` (an AudioBuffer) at `speedRatio` times the speed, same pitch. */
export function changeTempo(context, buffer, speedRatio) {
  const channels = [];
  for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
    const samples = buffer.getChannelData(ch);
    channels.push(timeStretch({ samples, sampleRate: buffer.sampleRate, speedRatio }));
  }
  const out = context.createBuffer(channels.length, channels[0].length, buffer.sampleRate);
  channels.forEach((data, ch) => out.copyToChannel(data, ch));
  return out;
}

The output holds the input length divided by speedRatio, rounded up. timeStretch takes one channel at a time, so the function stretches each channel of a stereo buffer on its own. The timing offset between the two channels survives, but their correlation does not fully: a wide, diffuse stereo mix can lose some focus.

Beyond tempo, this page covers the other offline edits that move time or pitch on decoded mono samples: pitch shift, formant shift, stretching one note region and voiceChange. To pull a vocal onto a note or a key, see Pitch Correction; for the units every call here shares, see Editing DSP.

If semitone or formant are unfamiliar, read Editing Basics first.

Which Call Do You Need? ​

GoalUseBeginner note
Make a clip longer or shorter without changing the notetimeStretchspeedRatio is a playback-speed multiplier: speedRatio: 2 plays twice as fast, so the clip is half as long; speedRatio: 0.5 is half speed and twice as long. The pitch does not change. (Note: noteStretch's stretchRatio is a length multiplier, so it works the opposite way.)
Move the whole clip up or down in pitchpitchShiftpitchSemitones: 12 means one octave up; -12 means one octave down
Hold or shorten one note regionnoteStretchRegion positions are samples or seconds (onsetSec / offsetSec), never negative; stretchRatio > 1 lengthens the replacement region, and the whole-clip shift follows that region-length change
Change vocal charactervoiceChangePitch changes the note; formant changes the perceived body or character of the voice
PARAM SWEEP · FORMANTIDLE
Formant shift — changing character, not pitch

Formant shifting is pitch shift's counterpart: it moves the spectral envelope — the formant peaks that make a voice feel small and bright or large and dark — while leaving the note alone. Drag the factor and watch the harmonic comb and the fundamental marker hold their place as the envelope slides. Above 1.0 the voice brightens and shrinks; below 1.0 it darkens and enlarges; the pitch never changes. Press play to hear the character shift with no retuning.

Preview
Switching during playback restarts the selected audio from the beginning.Processed
Formant
1 ×
PARAM SWEEP · PITCH SHIFTIDLE
Pitch shift — moving the whole harmonic comb

Pitch shifting transposes a sound without changing its length. Drag the semitones and watch the spectrum: every harmonic scales together and the fundamental marker tracks the new pitch. Because this shift is not formant-preserving, the formant bumps move too — the "chipmunk" effect. Press play to hear it.

Preview
Switching during playback restarts the selected audio from the beginning.Processed
Pitch
0 st
PARAM SWEEP · TIME STRETCHIDLE
Time stretch — changing length, not pitch

Time stretching changes duration while keeping pitch approximately unchanged. A rate below 1 slows and lengthens the clip; a rate above 1 speeds and shortens it. The waveform shows the duration change. Each render is peak-normalized for headroom, which does not equalize perceived loudness. Listen for changes in timing and transient clarity.

Preview
Switching during playback restarts the selected audio from the beginning.Processed
Rate
1 ×
What is a formant?

A formant is a peak of acoustic energy in a particular frequency range. It is created by resonances of the vocal tract.

Formants shape the vowel sound and the perceived size or character of a voice, independent of the pitch (the note being sung).

That is why voiceChange separates the two controls. Lowering the formant factor makes a voice sound larger and darker. Raising it makes the voice sound smaller and brighter. The note stays where pitchSemitones puts it, because the formant stage moves only the spectral envelope.

Usage ​

typescript
import { init, noteStretch, pitchShift, timeStretch, voiceChange } from '@libraz/libsonare';

await init();

const slower = timeStretch({ samples: vocal, sampleRate, speedRatio: 0.8 });
const higher = pitchShift({ samples: vocal, sampleRate, pitchSemitones: 2 });
const heldNote = noteStretch({ samples: vocal, sampleRate, onsetSample: 12000, offsetSample: 24000, stretchRatio: 1.25 });
const character = voiceChange({ samples: vocal, sampleRate, pitchSemitones: 5, formantFactor: 1.1 });
typescript
import { Audio, noteStretch, pitchShift, timeStretch, voiceChange } from '@libraz/libsonare-native';

const audio = Audio.fromFile('vocal.wav');
const { data: samples, sampleRate } = audio;

const slower = timeStretch({ samples, sampleRate, speedRatio: 0.8 });
const higher = pitchShift({ samples, sampleRate, pitchSemitones: 2 });
const heldNote = noteStretch({ samples, sampleRate, onsetSample: 12000, offsetSample: 24000, stretchRatio: 1.25 });
const character = voiceChange({ samples, sampleRate, pitchSemitones: 5, formantFactor: 1.1 });
python
import libsonare as sonare

slower = sonare.time_stretch(vocal, sample_rate, speed_ratio=0.8)
higher = sonare.pitch_shift(vocal, sample_rate, pitch_semitones=2)
held_note = sonare.note_stretch(vocal, sample_rate, onset_sample=12000, offset_sample=24000, stretch_ratio=1.25)
character = sonare.voice_change(vocal, sample_rate, pitch_semitones=5, formant_factor=1.1)
bash
# The sonare CLI loads and writes WAV/MP3 directly
sonare time-stretch vocal.wav --rate 0.8 -o slower.wav
sonare pitch-shift vocal.wav --pitch-semitones 2 -o higher.wav
sonare note-stretch vocal.wav --onset-sample 12000 --offset-sample 24000 --ratio 1.25 -o held.wav
sonare voice-change vocal.wav --pitch-semitones 5 --formant-factor 1.1 -o character.wav

The CLI's --rate is the same multiplier as speedRatio. Each helper returns the processed samples; none of them changes its input.

formantFactor is applied after the pitch shift

voiceChange transposes first, and a transpose already drags the formants with it. The formant stage then runs on that shifted signal, so formantFactor multiplies a displacement that is already there. formantFactor: 1.0 means "no extra formant move", not "formants preserved" — { pitchSemitones: 5, formantFactor: 1.1 } above lands the formants at roughly 25/12 × 1.1 ≈ 1.47×, which is a deliberate character change rather than a transparent transpose.

For a natural-sounding transpose, cancel the pitch-induced move by passing the reciprocal of the pitch ratio:

typescript
const pitchSemitones = 5;
const transposed = voiceChange({
  samples: vocal,
  sampleRate,
  pitchSemitones,
  formantFactor: 2 ** (-pitchSemitones / 12), // 0.749 — keeps the vocal tract where it was
});

formantMode: 'absolute' does that bookkeeping for you. formantFactor is then the formant shift relative to the input, whatever the pitch shift, and 1 keeps the formants where they were; the warp actually applied is formantFactor / 2^(pitchSemitones / 12). The default, 'relative', is the behavior described above.

typescript
const natural = voiceChange({
  samples: vocal,
  sampleRate,
  pitchSemitones: 5,
  formantFactor: 1,       // formants stay at the input's position
  formantMode: 'absolute',
});

Absolute mode limits how far the formants can be held against the pitch shift; a request outside that limit throws a RangeError and is never clamped. In the default relative mode formantFactor itself must lie in [0.55, 1.65] and is refused outside it (RangeError on Node and WASM, SonareValueError on Python). Python and the voice-change CLI (--formant-mode) refuse it the same way.

For rectangular time/frequency edits such as whistle attenuation or short artifact repair, see Spectral Editing.

Region selection for noteStretch(...) ​

noteStretch(...) takes the region in samples (onsetSample, offsetSample) or in seconds (onsetSec, offsetSec); see Samples and seconds. onsetSample defaults to the start of the input and offsetSample to its end, so omit a boundary when the region already reaches that edge.

typescript
const heldNote = noteStretch({ samples: vocal, sampleRate, onsetSec: 0.25, offsetSec: 0.5, stretchRatio: 1.25 });

noteMove(...) takes the same bounds plus exactly one of targetOnsetSample / targetOnsetSec, the position the note's onset moves to. Omitting both targets or supplying both is refused.

stretchRatio is the nominal length multiplier for the selected region. noteStretch blends the source samples at the replacement region's start and end with crossfades whose weights follow how alike the two sides are. Those crossfades stay inside the replacement region and do not consume neighboring samples. The output clip length and the shift of audio after the region therefore follow the replacement region's length change. stretchRatio: 1.0 keeps the whole clip length neutral; for other ratios, the time-stretch backend can round the replacement length by a few samples. A clip edge has no neighboring audio on that side, so it has no crossfade there.

The stretched region and the source it blends with are closely related, so a fixed equal-power crossfade would move the level inside a seam. Each seam is instead weighted by the correlation of its two sides, and the stretched copy is placed where its seams line up in phase. On a steady 440 Hz tone stretched by 0.8, 1.25 and 1.5, the output level measured over three-cycle windows stays within 0.01 dB of the tone, seams included. Fade curves and crossfades explains the correlation rule.

stretchRatioResult
1.25Make the replacement region 25% longer; following audio shifts later by that region-length increase, subject to sample rounding
1.0Keep the replacement region and whole clip at the same length
0.8Make the replacement region 20% shorter; following audio shifts earlier by that region-length decrease, subject to sample rounding

Using Audio methods ​

The Audio object exposes the same operations as methods, so a file loaded once can be edited without passing its samples and sample rate every time. The JavaScript methods take the options object alone; the Python ones take the amounts positionally or by keyword.

typescript
import { Audio } from '@libraz/libsonare-native';

const audio = Audio.fromFile('vocal.wav');
const slower = audio.timeStretch({ speedRatio: 0.8 });
const character = audio.voiceChange({ pitchSemitones: 5, formantFactor: 1.1 });
python
import libsonare as sonare

audio = sonare.Audio.from_file("vocal.wav")
slower = audio.time_stretch(0.8)
character = audio.voice_change(pitch_semitones=5, formant_factor=1.1)

Offline transforms vs arrange-time warp

The functions on this page are offline transforms: you hand them a buffer and get a new buffer back. They are different from arrange-time warp — clip repitch and tempo-sync inside a project, where a clip follows the timeline rather than being baked once. For that project-level workflow, see Project Editing.

For note-by-note edits that are rendered back into audio, see Note Editing in Audio. For edits that change a project MIDI clip, see MIDI Editing.

To run the same voice processing on live blocks instead of a whole buffer, see Offline voiceChange(...) vs RealtimeVoiceChanger.