DEV Community

Tania Alwan
Tania Alwan

Posted on

Time Stretching Explained: How to Change Tempo Without Changing Pitch (With a Python Example)

By Tania Alwan

Slow down a YouTube video to 0.75x and the voice still sounds like the same person, just slower. Do the same thing with an old tape deck and everyone suddenly sounds like a giant. The difference is time stretching: changing the duration of audio while keeping its pitch. This post explains why the naive approach fails, how the classic phase vocoder fixes it, and ends with a short Python script you can run.

The problem in one sentence

Pitch and duration are tied together in a waveform: play the samples faster and every cycle gets shorter, so the frequency goes up.

That is exactly what happens when you resample audio or speed up a tape. A 25% speed-up raises every frequency by 25%, which is close to four semitones. Time stretching is the set of tricks that breaks that link.

Approach 1: Cut, overlap and add (OLA and WSOLA)

The simplest idea works in the time domain:

  • Chop the signal into short overlapping chunks (often 20 to 100 ms)
  • Space the chunks further apart (to slow down) or closer together (to speed up) when you glue them back
  • Crossfade the overlaps with a window so there are no clicks

Plain overlap-add (OLA) creates phasing and warbly artifacts because the waveforms in neighbouring chunks no longer line up. WSOLA (waveform-similarity overlap-add) improves this by nudging each chunk a little in time to find the position where it best matches the previous one. It works well for speech and monophonic material, which is why it shows up in many playback-speed features.

Approach 2: The phase vocoder

The phase vocoder works in the frequency domain:

  1. Compute a short-time Fourier transform (STFT): a sequence of spectra, one per frame
  2. Keep the magnitudes of each frequency bin as they are
  3. Re-space the frames in time (for example, read them at 1.25x the rate)
  4. Recompute the phases so each bin keeps advancing at the right speed for its frequency
  5. Run the inverse STFT to get audio back

Step 4 is the important one. If you just reuse the old phases, sinusoids jump from frame to frame and you hear garbage. By tracking how much each bin's phase should advance between frames, the vocoder keeps the frequency constant while the duration changes.

The Python example

This script makes two seconds of a 440 Hz tone (A4), then speeds it up by 25% in two ways: naive resampling and librosa's phase-vocoder time stretch. It prints the new duration and the dominant frequency of each version.

import numpy as np
import librosa

sr = 22050
t = np.linspace(0, 2.0, int(sr * 2.0), endpoint=False)
y = 0.5 * np.sin(2 * np.pi * 440.0 * t)  # 2 seconds of A4

def dominant_freq(signal, sr):
    spectrum = np.abs(np.fft.rfft(signal * np.hanning(len(signal))))
    freqs = np.fft.rfftfreq(len(signal), 1 / sr)
    return freqs[np.argmax(spectrum)]

# Naive approach: resample (like speeding up a tape)
naive = librosa.resample(y, orig_sr=sr, target_sr=int(sr / 1.25))

# Phase-vocoder time stretch: faster, same pitch
stretched = librosa.effects.time_stretch(y, rate=1.25)

for name, sig in (("original", y), ("resampled", naive), ("time_stretch", stretched)):
    print(f"{name:13s} {len(sig) / sr:.2f} s  {dominant_freq(sig, sr):.0f} Hz")
Enter fullscreen mode Exit fullscreen mode

Output:

original      2.00 s  440 Hz
resampled     1.60 s  550 Hz
time_stretch  1.60 s  440 Hz
Enter fullscreen mode Exit fullscreen mode

Both versions are 1.6 seconds long, but only the time-stretched one is still an A. The resampled one jumped to 550 Hz.

To try it on a real file, replace the synthetic tone with y, sr = librosa.load("vocal.wav") and write the result with soundfile.write("out.wav", stretched, sr). Use rate < 1 to slow down.

Why real recordings are harder

A pure sine wave is the friendliest possible input. Real audio exposes the weak spots of each method:

  • Transients get smeared. Drum hits and consonants spread across a whole STFT frame, so a stretched snare can sound soft or "phasey". Better algorithms detect transients and treat them separately.
  • Phasiness on polyphonic material. A basic phase vocoder loses the phase relationships between neighbouring bins, which gives a distant, swirly sound. Techniques such as phase locking reduce it.
  • Big ratios sound unnatural. Small changes are usually transparent; stretching a vocal to half speed or less often gets audible artifacts with any method.
  • Mixed material is a compromise. A setting that suits vocals may smear drums. Stretching stems separately, then mixing them back, often sounds cleaner.

That last point is why stem separation and time stretching are often combined in practice. Open-source models like Demucs run locally, and hosted tools such as the Voicestars stems splitter do it in the browser. Either way you can stretch the vocal with one setting and the drums with another.

Where you meet time stretching every day

  • Playback-speed controls in video and podcast apps
  • DAW features that fit a loop or sample to the project tempo (warping, elastic audio, flex time)
  • DJ software that keeps a track's key while matching tempos
  • Practice tools that slow a song down so you can learn a part

Takeaways

  • Resampling changes tempo and pitch together; time stretching changes tempo only.
  • Time-domain methods (WSOLA) cut and realign chunks; the phase vocoder re-spaces spectral frames and fixes the phases.
  • Transients and dense mixes are where artifacts appear, so smaller ratios and separated stems help.
  • librosa.effects.time_stretch is a quick way to experiment before reaching for dedicated libraries such as Rubber Band.

Disclosure: this article was written in partnership with Voicestars.

Top comments (0)