Time-Stretching Audio Without Changing Its Pitch
Why speeding up audio raises its pitch, and how overlap-add, WSOLA and the phase vocoder change duration without changing pitch, plus the right way to shift pitch without changing length.
If you speed up a tape recorder, two things happen at once: the music finishes sooner, and everyone sounds like a chipmunk. Duration and pitch are welded together because you are literally pushing the same waveform past the playhead faster. Every cycle of every note completes in less time, so its frequency goes up. That is resampling, and it is the simplest, cheapest way to change the speed of audio.
Most of the time, though, when we say "speed this podcast up to 1.5x" we do not want the chipmunk. We want the talking to go faster while the voice stays recognizably the same. That requires a fundamentally different operation: changing how long the audio lasts without changing the frequencies inside it. The two operations look alike in an interface (both have a speed slider), but the signal processing underneath has almost nothing in common.
This post walks through both, from the index arithmetic of resampling to the overlap-add family of time-stretchers. It also covers the inverse problem, changing pitch without changing duration, because once you understand one, the other is the same trick run in the opposite direction.
Resampling: the tape effect
Resampling is index arithmetic. To play audio at speed times the original rate, you produce an output buffer that is 1/speed as long, and for each output sample you read from a position in the source that advances by speed samples per output sample.
A minimal version looks like this:
function resample(input, speed) {
const outLength = Math.floor(input.length / speed);
const output = new Float32Array(outLength);
for (let i = 0; i < outLength; i++) {
const pos = i * speed; // walk the source faster than the output
const i0 = Math.floor(pos);
const i1 = Math.min(i0 + 1, input.length - 1);
const frac = pos - i0;
output[i] = input[i0] * (1 - frac) + input[i1] * frac; // linear interpolation
}
return output;
}
At speed = 2, pos lands on 0, 2, 4, 6 and so on, so you skip every other sample and the output is half as long. Because pos is usually fractional (at speed = 1.5 you need samples 1.5, 3.0, 4.5...), you cannot just read an integer index; you have to interpolate. Linear interpolation between the two nearest samples is the simplest choice. Cubic interpolation across four neighbours traces a smoother curve and adds less high-frequency grit, at a small extra cost.
The key consequence is that every frequency in the signal scales by speed. A 200 Hz note read back twice as fast completes each cycle in half the time, so it comes out at 400 Hz. That is exactly the tape effect, and for some uses it is exactly what you want: pitch up a drum loop, drop a vocal an octave for a spooky effect, or just go fast for comedic value.
Interpolation is only half of a good resampler. When you speed audio up, high frequencies climb too, and anything pushed above the Nyquist frequency (half the sample rate) cannot be represented. It folds back down as aliasing, an inharmonic whistle that has nothing to do with the music. At 2x on 44.1 kHz audio, a 15 kHz cymbal shimmer would need to become 30 kHz, which is past the 22.05 kHz limit, so it reflects down to 14.1 kHz instead. A proper resampler low-pass filters the source first, removing everything above the Nyquist frequency divided by the speed factor, and only then reads it faster.
The Web Audio API has this operation built in:
source.playbackRate.value = speed;
AudioBufferSourceNode.playbackRate is resampling done by the browser's own audio engine, so pitch rides along with speed. That makes it a nearly free way to preview the tape effect, and you can change the value mid-playback and the running source follows. Media elements behave differently: <audio> and <video> have a playbackRate too, but their preservesPitch property is on by default, so the browser time-stretches for you there.
Why you cannot keep pitch by resampling
It helps to state plainly why resampling can never preserve pitch, because it explains why the second algorithm has to exist. Pitch is frequency. Frequency is cycles per second. If you keep all the samples but play them out over a shorter stretch of wall-clock time, you have packed more cycles into each second by definition. No resampling ratio shortens the audio without raising its frequency, because those are the same number.
To decouple them you have to do something that feels almost like cheating: keep the local shape of the waveform intact (so frequencies stay put) while changing how many of those local shapes you lay down end to end (so duration changes). That is what overlap-add time-stretching does.
Granular overlap-add time-stretching
The idea is to chop the source into short, overlapping grains, then place those grains onto the output timeline at a different spacing from the one you read them at. Read grains close together in the source but write them farther apart in the output, and the audio gets longer. The grains themselves are never resampled, so the waveform inside each one keeps its original frequencies.
The plainest form of the technique, called overlap-add (OLA), fits in a few lines:
function stretch(input, rate) {
const N = 2048; // grain length in samples
const hop = N / 4; // write step: 512 samples
const outLength = Math.floor(input.length / rate);
const output = new Float32Array(outLength);
let readPos = 0;
for (let writePos = 0; writePos + N <= outLength; writePos += hop) {
const start = Math.min(Math.floor(readPos), input.length - N);
for (let i = 0; i < N; i++) {
const w = 0.5 * (1 - Math.cos((2 * Math.PI * i) / N)); // Hann window
output[writePos + i] += (input[start + i] * w) / 2; // 4 overlapping windows sum to 2
}
readPos += hop * rate; // read pointer moves at the playback rate
}
return output;
}
Two things make this work, and both are visible in the loop.
First, the write pointer always advances by hop (512 samples) while the read pointer advances by hop * rate. That decoupling is the whole game. At rate = 2 (twice as fast), the read pointer jumps 1024 source samples each iteration while the write pointer moves only 512 output samples, so you consume the source twice as fast as you fill the output, and the output ends up half as long. At rate = 0.5, you barely move through the source while filling the output at the normal pace, so the output is twice as long. The output length is floor(input.length / rate), the same as for resampling, so the duration math is identical even though the mechanism is not.
Second, the Hann window (0.5 * (1 - cos(2πi/N))) tapers each 2048-sample grain to zero at both edges. This is essential. If you chopped the audio into rectangular blocks and laid them down at new positions, every grain boundary would be a discontinuity, and discontinuities in a waveform are clicks. The window fades each grain in and out, and because consecutive grains overlap (the hop is 512 but the grain is 2048, so four grains cover every point), the fading tail of one grain is filled in by the rising head of the next. The grains are summed into the output with +=, which is the "add" in overlap-add.
The overlap factor is N / hop = 2048 / 512 = 4. Four Hann windows spaced a quarter-window apart sum to exactly 2 at every point, which is why the snippet divides by 2: on unchanged audio the output comes back at its original level instead of pulsing. Once the read and write rates differ, the overlapping grains come from different parts of the source and no longer line up perfectly, so the sum can still overshoot here and there. A cheap safety net is a final peak check:
let peak = 0;
for (const s of output) peak = Math.max(peak, Math.abs(s));
if (peak > 1) {
for (let i = 0; i < output.length; i++) output[i] /= peak;
}
That is peak normalization, not a limiter: it scales the whole channel uniformly so nothing clips.
Resampling vs overlap-add at a glance
| Property | Resampling (tape) | Overlap-add stretch |
|---|---|---|
| Changes duration | Yes | Yes |
| Changes pitch | Yes (scales with speed) | No (preserved) |
| Cost | Very cheap (one pass, interpolation) | Higher (overlapping grains, windowing) |
| Read vs write pointer | Move together at speed | Decoupled: read at hop * rate, write at hop |
| Main artifact | Aliasing if not low-pass filtered, grit if interpolation is crude | Transient smearing, phasiness at extremes |
| Good for | Effects, intentional pitch change | Podcasts, speech, keeping a voice natural |
Where overlap-add breaks down
Grain-based stretching is not artifact-free, and the artifacts get worse as the ratio moves away from 1.0.
The most audible problem is transient smearing. Sharp attacks (a snare hit, a consonant like "t" or "k", a plucked string) are short events. When you stretch time, you duplicate and overlap grains, and a transient that fell inside one grain gets spread across the overlap region of several. The attack softens and can even double. Drums stretched slowly take on a flammed, mushy quality.
The second problem is phasiness, a hollow, slightly metallic or "underwater" coloration. Plain OLA copies grains without regard to the phase of the waveforms inside them. When a grain read from one point in the source lands on top of a grain read from another, their cycles rarely line up, and the partial cancellation tints the sound and makes steady tones warble.
There are two classic fixes:
- WSOLA (waveform similarity overlap-add) stays in the time domain. Before placing each grain, it searches a small range around the nominal read position for the offset whose waveform best continues what was just written, then reads from there. The grains still advance through the source at the right average rate, but each one is nudged into phase with its neighbour.
- The phase vocoder works in the frequency domain. It takes an FFT of each grain and tracks and corrects the phase of every frequency bin from one grain to the next, so the partials stay continuous however the grains are spaced.
The heart of WSOLA is a short similarity search:
// Find the start position near `target` whose waveform best matches
// `natural`: where the source would have continued from the previous grain.
function bestStart(input, target, natural, length, range) {
let best = target;
let bestScore = -Infinity;
for (let d = -range; d <= range; d++) {
const start = target + d;
if (start < 0 || start + length > input.length) continue;
let score = 0;
for (let i = 0; i < length; i++) score += input[start + i] * input[natural + i];
if (score > bestScore) { bestScore = score; best = start; }
}
return best;
}
In the stretch loop, target is the rounded read position and natural is the previous grain's start plus one hop. The search range only needs to span about one cycle of the lowest pitch you care about, typically 10 to 20 ms. Real implementations usually normalize the correlation (so loud passages do not win by default) or use a cheaper measure such as the sum of absolute differences, but the principle is the same. Dedicated libraries take this much further: SoundTouch (and its JavaScript port, SoundTouchJS) is built on this time-domain approach, while Rubber Band is built on a phase vocoder with extra handling for transients.
In practice, gentle ratios near 1.0 hold together well, and smearing and phasiness become more obvious the further you push toward an octave of stretch (roughly 0.5x or 2x), especially on music with strong transients. WSOLA shines on speech and other material with one clear pitch at a time, because there is one periodicity to line up. Dense polyphonic music is harder, since no single offset can align every instrument at once. Speech and podcasts also tolerate stretching better than percussive music because the ear is forgiving about the exact attack of a spoken consonant but very sensitive to a smeared drum.
The inverse operation: pitch shift without duration change
Pitch shifting is time-stretching run backwards. If you can change duration without touching pitch, you can change pitch without touching duration by combining a stretch with a resample.
To raise pitch by n semitones, you want a frequency multiplier of 2^(n/12) (twelve semitones double the frequency: one octave). First, time-stretch the audio so it becomes that many times longer, with its pitch untouched. Then resample it by the same ratio, which shortens it back to the original length and multiplies every frequency by the ratio. The two length changes cancel and the pitch change remains:
function pitchShift(input, semitones) {
const ratio = Math.pow(2, semitones / 12); // +12 semitones = 2x frequency
const longer = stretch(input, 1 / ratio); // ratio times longer, same pitch
return resample(longer, ratio); // original length, pitch times ratio
}
Rounding in the two steps can leave the result a sample or two off, so in practice you trim or pad to the exact original length. Lowering pitch works the same way with a negative n: the stretch shortens the audio and the resample stretches it back out.
A tempting shortcut is to do everything in a single grain loop: keep the read and write grain positions in step (so the length never changes) and resample inside each grain. It looks right on paper but tends to sound wrong. At any output instant, the overlapping grains are reading the source from slightly different places, so on a steady tone they arrive with different phases and partly cancel, leaving a weaker, rougher sound whose strongest partial can drift away from the target. Treating the stretch and the resample as two separate, well-behaved steps avoids that.
The usual artifacts carry over from the stretcher: shift by an octave in either direction and transient smearing and phasiness become obvious. Within a few semitones the result holds together well, and the safest adjustment of all is a matter of cents (1/100 of a semitone, a ratio of 2^(c/1200)), which is handy for nudging a recording toward A440. Keep in mind that this method moves everything, including the formants, the resonances that give a voice its character. A voice shifted up an octave keeps its length but still sounds smaller; preserving formants takes spectral-envelope processing on top.
The other option is to skip the stretch and only resample, which is vari-speed: pitch and duration move together, there are no grain artifacts, but you cannot keep the length. You might be tempted to fake vari-speed by relabeling the sample rate instead, telling the player that 44,100 Hz audio is really 88,200 Hz for an octave up. Playback sounds right, but the file now has a non-standard rate that many formats (MP3 included) cannot store, so a real, band-limited resample is the safer route.
Putting it together
The mental model that ties all of this together is two independent pointers and a windowed grain:
- Move read and write pointers together, scaling the read step: resampling. Cheap, with pitch and duration locked.
- Move them at different rates and copy grains 1:1: time-stretch. Duration changes, pitch holds.
- Stretch, then resample by the same ratio: pitch shift. Pitch changes, duration holds.
Everything here is built from the same few parts: interpolation, a Hann-windowed grain, a hop, and overlap-add summation, with WSOLA's similarity search or a phase vocoder layered on top to keep the grains in phase. That covers most of what production time and pitch engines do. The rest of their sophistication goes into transient detection and smarter phase handling to clean up the artifacts described above.
Try it yourself
To hear the difference, open the Loopaloo Audio Speed Adjuster. Set any speed from 0.25x to 4x, or use the 0.5x to 2x presets. With "Preserve Pitch" on, it uses a WSOLA time stretch, so the tempo moves and the pitch stays; turn it off for band-limited vari-speed, the tape effect without the aliasing. After each render it measures the output and shows how far the pitch actually moved, in cents: close to zero with pitch preserved, and about +1200 cents (one octave) for vari-speed at 2x.
The Pitch Shifter runs the inverse operation. Move by up to an octave in semitone steps, fine-tune by ±50 cents, and choose "Keep length" for a stretch-then-resample shift or "Vari-speed" to let the length change. It, too, analyses what it produced and shows the error against the interval you asked for. Both tools decode and process entirely in your browser and export WAV or MP3, so nothing leaves your machine.
Related Tools
Audio Speed Changer
Speed up or slow down audio from 0.25x to 4x, keeping the original pitch or letting it rise and fall like tape. Download as WAV or MP3.
Audio Pitch Shifter
Change the pitch of a song or recording by semitones without changing its speed, to move it into a better key. Preview, then download WAV or MP3.