Algorithmcore
Phase vocoder
Also called phase vocoder time stretching.
Time-stretch or pitch-shift audio by changing the hop of the STFT and advancing each bin's phase by its estimated instantaneous frequency.
- Time
- O(F N log N) worst
- Space
- O(N) extra
- Where
- F = the number of analysis frames; N = the frame and FFT length
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James L. Flanagan, Roger M. Golden, 1966
The phase vocoder changes the duration of a sound without changing its pitch, or the pitch without changing the duration. It takes the short-time Fourier transform of the input with a hop , keeps the magnitude of each bin, gives each bin a new phase that advances by times the bin's instantaneous frequency, and puts the frames back with overlap-add at a hop . PSOLA does the same jobs in the time domain, one pitch period at a time, and works better on a single voice; the phase vocoder needs no pitch marks and works on any sound.
In plain words
Cut the sound into short, overlapping pieces and find which frequencies are in each piece. To make the sound slower, put the pieces back farther apart than they were cut. If you only move the pieces, the waves in neighboring pieces no longer line up where they overlap, and they cancel or beat. So for each frequency the method measures how far the wave turned between two input pieces, works out the exact frequency from that turn, and turns the wave by the correct, larger amount between two output pieces. The waves then line up again. The result is longer, but every tone keeps its frequency. To raise the pitch, stretch first and then play the result faster.
The problem
Given a signal and a ratio , produce a signal of about times the duration of in which every stationary sinusoid of appears with the same frequency and amplitude. A pitch shift by a factor is a stretch by followed by sample-rate conversion by . There is no single correct output for a general sound, so the requirement is exact only for sinusoids.
The algorithm
Let be a window of length , let be the center of bin , let , and let map an angle to by adding a multiple of .
PHASE-VOCODER-STRETCH(x, alpha, window w of length N, analysis hop Ha)- 1
X_t <- FFT(w * x[t Ha .. t Ha + N - 1]) for t = 0 .. F - 1 - 2
psi <- arg X_0; the first output frame is IFFT(X_0) - 3
for t <- 1 to F - 1 do - 4
delta_k <- princarg(arg X_t[k] - arg X_{t-1}[k] - Ha omega_k) for every bin k - 5
omega'_k <- omega_k + delta_k / Ha (the instantaneous frequency) - 6
psi_k <- psi_k + Hs omega'_k - 7
the output frame t is IFFT(|X_t[k]| e^{i psi_k}) - 8
y <- sum over t of w * frame t at t Hs, divided by the sum of w^2 at t Hs
Lines L4 and L5 are the core. The phase of bin moves by between two frames if the bin holds a sinusoid of frequency . The measured phase change is only known up to a multiple of , so the expected part is taken away and the rest is wrapped to . If the true frequency is within of the bin center, the wrapped rest is exactly . Line L8 is the weighted overlap-add, which divides by the sum of the squared windows.
Example
Take Hz, , with the periodic Hann window, and a sine of 440 Hz with amplitude 0.5. The bins are 7.8125 Hz apart, and the largest one in each frame is at 437.5 Hz, with magnitude 119.77.
- The phases of bin 56 in frames 0 and 1 are and rad.
- The expected advance is rad.
- The raw rest wraps to rad.
- So rad per sample, which is Hz.
The bins 55, 57 and 58, with magnitudes 35.1, 94.1 and 11.2, also give 440.0000 Hz: all the bins near a sinusoid estimate the same frequency. A stretch by has , so each output frame advances the phase of these bins by rad. The 4096 input samples give 13 frames and output samples. Measured by the zero crossings in the middle of the signals, the input is at 440.17 Hz and the output at 440.09 Hz, with a peak of 0.515. A pitch shift by 1.25 gives 549.97 Hz.
Correctness
These are theorems, proved in proofs/correctness.md:
- Exact frequency for one exponential. If and , then line L5 gives exactly, for any window.
- Identity. If , every output frame equals the analysis frame, and the output equals at every sample where the sum of the squared windows is not 0.
- Exact stretch of one exponential. If and the condition above holds in every bin where , then output frame is , and the overlap-add gives : the same frequency and amplitude, at any length. With the periodic Hann window and on a bin center, this holds for every .
A real sinusoid is the sum of two exponentials, and their leakage into each other's bins makes the estimate only close; the 440.0000 Hz above is a measurement. For sounds with several sinusoids in one bin, or with fast changes, the method is a heuristic, and its errors are the artifacts listed under Pitfalls.
Proof: Correctness of the phase vocoderfull
The phase vocoder has no exact specification for a general sound, so we prove what it does exactly: the frequency estimate is exact for a complex exponential, equal hops give back the input, and a complex exponential is stretched with no change of frequency or amplitude.
Setup
The window has length . Frame of the analysis is with . The function returns the unique value in that differs from by an integer multiple of . Write . The algorithm sets and, for ,
and output frame is with . The output is with , at every with (terms with the index outside are 0).
Lemma 1 (the overlap-add inverts windowed frames)
If for all and , for some signal , then the weighted overlap-add at hop returns at every with .
Proof. . Divide by .
Theorem 1 (exact frequency for one exponential)
Let with , and let be a bin with and . Then for every .
Proof. Substituting ,
So and for some integer . The argument of princarg is . The value is in and differs from it by a multiple of , so princarg returns it. Then .
Theorem 2 (identity for equal hops)
If , then for every , and at every with .
Proof. We show by induction on . It holds for . For , princarg changes its argument by a multiple of , so
which is plus a multiple of by the hypothesis. Hence (for both sides are 0). The IFFT inverts the FFT, so , and Lemma 1 with gives where .
Theorem 3 (a complex exponential is stretched exactly)
Let , and suppose every bin with satisfies . Then for any , at every with .
Proof. Take a bin with . By Theorem 1, , and by the formula in its proof. So . For a bin with , also and . Hence and
which is the windowed frame of the signal at hop . Lemma 1 gives where .
For example, with the periodic Hann window and on a bin center, only for , and the condition holds whenever .
Remarks
Real signals. For a real input, . Since and except when is an odd multiple of , the updates give modulo outside that case, so is conjugate symmetric and is real. The code takes the real part, which only removes rounding.
Real sinusoids. A real sinusoid is the sum of two exponentials, at and . Their sum in a bin is not of the form of Theorem 1, so the estimate is only close, with an error that falls as the window rejects the other exponential better. The tests measure 440.0000 Hz for a 440 Hz sine at .
The tests. The tests check Theorem 1 for complex exponentials at several frequencies, Theorem 2 on random noise (error below ) and Lemma 1 directly.
Complexity
With analysis frames of samples, each frame needs one FFT, phase updates and one inverse FFT, so the time is . A streaming version keeps one previous spectrum, the phase array and an output buffer of samples, so the extra memory is . The code on this page keeps all the frames for clarity. For a stretch of input samples, , so the cost per input sample is , which is for the usual overlap of 4.
Properties
- No pitch marks. Unlike PSOLA, it works on music, chords and noise, and needs no pitch detection.
- Constant frequency resolution. Every bin is wide. A long window resolves close partials but smears the onsets in time; a short window does the reverse.
- Online. Each output frame depends on two input frames, so the method can stream with a delay of one frame.
- Not exact for real signals. Only single exponentials are kept exactly; everything else is approximate.
Variants and improvements
- Phase locking. Laroche and Dolson lock the phases of the bins around each spectral peak to the phase of the peak, which keeps the vertical coherence across bins and reduces phasiness.
- Transient handling. Reset the phases to the analysis phases at detected onsets, so that drum hits stay sharp.
- Pitch shift. Stretch by , then resample by ; or move the bins in frequency directly and scale their phase advances.
- Phase from magnitude. When only magnitudes exist, as in neural speech synthesis, the Griffin-Lim algorithm finds phases that fit them by iteration.
When to use it
Use it to change the speed of music or other polyphonic sound, and for large stretch ratios. For a single voice with small changes of pitch and duration, as in text-to-speech by concatenation, PSOLA is cheaper and sounds more natural.
Pitfalls
- Phasiness. Each bin gets its own phase, so the bins of one partial drift apart and the sound gets a reverberant, distant quality. This is the main artifact of the basic method.
- Smeared transients. An attack is spread over a whole window and repeated by the overlap.
- Hop too large. The estimate is exact only in the bins whose center is within of the frequency, that is within bins. The main lobe of the Hann window covers the bins up to 2 bins from the frequency, so all of them are inside only if . The usual choice is at this limit, and the outer bins of the lobe can then get a wrong frequency.
- Window sum. Without dividing by the sum of the squared windows, the output gets an amplitude ripple at the hop rate, because for most synthesis hops this sum is not constant over time.
- Formants in pitch shifting. Resampling moves the spectral envelope with the pitch, so a voice shifted up by more than a few semitones sounds smaller. Keep the envelope apart, as in the source-filter model.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small signal processing tools for the natural-language-and-speech pages.
A signal is a list of floats x[0], ..., x[L - 1], usually in [-1, 1]. A frame is
a list of floats. A spectrum is a list of floats or complex numbers.
The defaults of the area are fs = 16000 Hz, frames of 400 samples (25 ms), a hop
of 160 samples (10 ms), the symmetric Hamming window and an FFT length of 512.
The LPC sign convention is A(z) = 1 - sum_{k=1}^{p} a_k z^-k, so the prediction
of x[n] is sum_{k=1}^{p} a_k x[n - k].
This module holds no algorithm of any page of the area: no mel scale, no mel
filter bank, no feature extractor, no pre-emphasis and no zero-crossing rate.
The pages build those on top of it.
"""
import cmath
import math
from typing import List, Sequence, Tuple
def frames(x: Sequence[float], frame_len: int, hop: int) -> List[List[float]]:
"""Cut x into frames of frame_len samples, one every hop samples, with no padding.
A signal of L >= frame_len samples gives 1 + (L - frame_len) // hop frames.
A signal shorter than one frame gives no frame. The last samples that do not
fill a frame are dropped.
"""
if frame_len <= 0 or hop <= 0:
raise ValueError("frame_len and hop must be positive")
n = len(x)
if n < frame_len:
return []
count = 1 + (n - frame_len) // hop
return [list(x[i * hop : i * hop + frame_len]) for i in range(count)]
def hamming(n: int) -> List[float]:
"""The symmetric Hamming window w[i] = 0.54 - 0.46 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
if n <= 0:
raise ValueError("the window length must be positive")
if n == 1:
return [1.0]
return [0.54 - 0.46 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]
def hann(n: int) -> List[float]:
"""The symmetric Hann window w[i] = 0.5 - 0.5 cos(2 pi i / (n - 1)), i = 0 to n - 1."""
if n <= 0:
raise ValueError("the window length must be positive")
if n == 1:
return [1.0]
return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / (n - 1)) for i in range(n)]
def fft(x: Sequence[complex]) -> List[complex]:
"""The DFT X[k] = sum_n x[n] exp(-2 pi i k n / N) by the iterative radix 2 FFT.
The length N must be a power of 2. The cost is O(N log N) operations.
"""
n = len(x)
if n == 0 or n & (n - 1):
raise ValueError("the FFT length must be a power of 2")
a = [complex(v) for v in x]
# bit reversal permutation
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
w_step = cmath.exp(-2j * math.pi / size)
for start in range(0, n, size):
w = 1.0 + 0.0j
for k in range(start, start + half):
u = a[k]
v = a[k + half] * w
a[k] = u + v
a[k + half] = u - v
w *= w_step
size *= 2
return a
def power_spectrum(frame: Sequence[float], nfft: int) -> List[float]:
"""|X[k]|^2 for k = 0 to nfft / 2, where X is the DFT of the frame zero padded to nfft."""
if len(frame) > nfft:
raise ValueError("the frame is longer than the FFT length")
spec = fft(list(frame) + [0.0] * (nfft - len(frame)))
return [abs(spec[k]) ** 2 for k in range(nfft // 2 + 1)]
def dct2(x: Sequence[float], k: int) -> List[float]:
"""The first k coefficients of the orthonormal DCT-II of x.
c[j] = s_j sum_{n=0}^{N-1} x[n] cos(pi j (2 n + 1) / (2 N)), with s_0 = sqrt(1 / N)
and s_j = sqrt(2 / N) for j >= 1. The full transform (k = N) is an orthogonal matrix.
"""
n = len(x)
if n == 0:
raise ValueError("empty input")
if k < 0 or k > n:
raise ValueError("k must be between 0 and len(x)")
out = []
for j in range(k):
s = math.sqrt((1.0 if j == 0 else 2.0) / n)
out.append(s * sum(x[i] * math.cos(math.pi * j * (2 * i + 1) / (2 * n)) for i in range(n)))
return out
def autocorr(x: Sequence[float], max_lag: int) -> List[float]:
"""r[k] = sum_{n=0}^{L-1-k} x[n] x[n + k] for k = 0 to max_lag (no normalization)."""
n = len(x)
return [sum(x[i] * x[i + k] for i in range(n - k)) if k < n else 0.0 for k in range(max_lag + 1)]
def levinson(r: Sequence[float], p: int) -> Tuple[List[float], float]:
"""Solve the normal equations of linear prediction of order p by the Levinson-Durbin recursion.
Returns (a, e): a = [a_1, ..., a_p] with A(z) = 1 - sum a_k z^-k, and e the
prediction error of order p. Needs r[0] > 0 and len(r) > p. If the error
reaches 0 before order p (a perfectly predictable signal), the remaining
coefficients are 0.
"""
if len(r) <= p:
raise ValueError("need r[0] to r[p]")
if r[0] <= 0:
raise ValueError("r[0] must be positive")
a = [0.0] * (p + 1) # a[0] is unused
e = float(r[0])
for i in range(1, p + 1):
if e <= 0.0:
break
acc = r[i] - sum(a[j] * r[i - j] for j in range(1, i))
k = acc / e
new = a[:]
new[i] = k
for j in range(1, i):
new[j] = a[j] - k * a[i - j]
a = new
e *= 1.0 - k * k
return a[1:], e
def sine(f: float, fs: float, n: int, amp: float = 1.0, phase: float = 0.0) -> List[float]:
"""x[i] = amp sin(2 pi f i / fs + phase) for i = 0 to n - 1."""
return [amp * math.sin(2.0 * math.pi * f * i / fs + phase) for i in range(n)]
def pulse_train(f0: float, fs: float, n: int) -> List[float]:
"""Unit pulses at the samples round(j fs / f0), j = 0, 1, 2, ..., and 0 elsewhere, n samples."""
if f0 <= 0:
raise ValueError("f0 must be positive")
x = [0.0] * n
period = fs / f0
j = 0
while True:
pos = int(math.floor(j * period + 0.5))
if pos >= n:
break
x[pos] = 1.0
j += 1
return x
def white_noise(rng, n: int, sigma: float) -> List[float]:
"""n samples of Gaussian noise with mean 0 and standard deviation sigma, from rng (a random.Random)."""
return [rng.gauss(0.0, sigma) for _ in range(n)]
def all_pole(x: Sequence[float], a: Sequence[float]) -> List[float]:
"""Filter x through 1 / A(z): y[n] = x[n] + sum_{k=1}^{p} a_k y[n - k], with zero initial state."""
p = len(a)
y: List[float] = []
for i, v in enumerate(x):
acc = float(v)
for k in range(1, p + 1):
if i - k < 0:
break
acc += a[k - 1] * y[i - k]
y.append(acc)
return y
phase_vocoder.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-vocoder/. The authors are listed in prov/M9RGV0.jsonl.
"""The phase vocoder: time stretching by the STFT with phase propagation.
Analysis frames start every Ha samples, synthesis frames every Hs samples, so the
duration changes by the factor Hs / Ha. Each bin keeps its magnitude. Its phase
is advanced by Hs times its instantaneous frequency, estimated from the phase
change between two analysis frames:
omega_k = 2 pi k / N (the bin center)
delta = princarg(phi_t[k] - phi_{t-1}[k] - Ha omega_k)
omega = omega_k + delta / Ha (the instantaneous frequency)
psi_t[k] = psi_{t-1}[k] + Hs omega (the synthesis phase)
where princarg maps an angle to [-pi, pi). The frames are put back by weighted
overlap-add: y = sum_t w(n - t Hs) frame_t(n - t Hs) / sum_t w(n - t Hs)^2.
"""
import cmath
import math
from typing import List, Sequence
from nlsdsp import fft
def princarg(phase: float) -> float:
"""The principal argument: phase + 2 pi m in [-pi, pi) for the integer m that puts it there."""
return phase - 2.0 * math.pi * math.floor((phase + math.pi) / (2.0 * math.pi))
def periodic_hann(n: int) -> List[float]:
"""w[i] = 0.5 - 0.5 cos(2 pi i / n): the Hann window whose shifts by n / 4 add to a constant."""
return [0.5 - 0.5 * math.cos(2.0 * math.pi * i / n) for i in range(n)]
def ifft(spec: Sequence[complex]) -> List[complex]:
"""The inverse DFT by the forward FFT of the conjugate."""
n = len(spec)
return [v.conjugate() / n for v in fft([s.conjugate() for s in spec])]
def stft(x: Sequence[float], n: int, hop: int, window: Sequence[float]) -> List[List[complex]]:
"""The DFTs of the windowed frames x[t hop .. t hop + n - 1]; the last partial frame is dropped."""
out = []
for start in range(0, len(x) - n + 1, hop):
out.append(fft([x[start + i] * window[i] for i in range(n)]))
return out
def instantaneous_frequency(prev: complex, cur: complex, k: int, n: int, hop: int) -> float:
"""omega_k + princarg(arg cur - arg prev - hop omega_k) / hop, in radians per sample."""
omega_k = 2.0 * math.pi * k / n
delta = princarg(cmath.phase(cur) - cmath.phase(prev) - hop * omega_k) # @line L4
return omega_k + delta / hop # @line L5
def overlap_add(frames: Sequence[Sequence[float]], hop: int, window: Sequence[float]) -> List[float]:
"""Weighted overlap-add: sum of window * frame at t hop, divided by the sum of window^2 where it is not tiny."""
n = len(window)
length = (len(frames) - 1) * hop + n if frames else 0
y = [0.0] * length
norm = [0.0] * length
for t, fr in enumerate(frames):
for i in range(n):
y[t * hop + i] += window[i] * fr[i]
norm[t * hop + i] += window[i] ** 2
return [v / z if z > 1e-8 else 0.0 for v, z in zip(y, norm)]
def time_stretch(x: Sequence[float], ratio: float, n: int = 1024, ha: int = 256) -> List[float]:
"""Stretch the duration of x by about ratio (> 1 is slower) and keep its pitch. n must be a power of 2."""
hs = round(ha * ratio)
window = periodic_hann(n)
spectra = stft(x, n, ha, window) # @line L1
if not spectra:
return []
psi = [cmath.phase(v) for v in spectra[0]] # @line L2
frames = [[v.real for v in ifft(spectra[0])]]
for t in range(1, len(spectra)): # @line L3
prev, cur = spectra[t - 1], spectra[t]
for k in range(n):
psi[k] += hs * instantaneous_frequency(prev[k], cur[k], k, n, ha) # @line L6
spec = [abs(cur[k]) * cmath.exp(1j * psi[k]) for k in range(n)] # @line L7
frames.append([v.real for v in ifft(spec)])
return overlap_add(frames, hs, window) # @line L8
def resample_linear(x: Sequence[float], factor: float) -> List[float]:
"""Read x at the positions i * factor by linear interpolation: factor > 1 makes it shorter and higher."""
out = []
pos = 0.0
while pos <= len(x) - 1:
i = int(pos)
frac = pos - i
nxt = x[i + 1] if i + 1 < len(x) else x[i]
out.append((1 - frac) * x[i] + frac * nxt)
pos += factor
return out
def pitch_shift(x: Sequence[float], factor: float, n: int = 1024, ha: int = 256) -> List[float]:
"""Raise the pitch by factor and keep the duration: stretch by factor, then resample by factor."""
hs = round(ha * factor)
return resample_linear(time_stretch(x, hs / ha, n, ha), hs / ha)
test_phase_vocoder.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-vocoder/. The authors are listed in prov/M9RGV0.jsonl.
import cmath
import math
import random
import unittest
from nlsdsp import fft, sine
from phase_vocoder import (
ifft,
instantaneous_frequency,
overlap_add,
periodic_hann,
pitch_shift,
princarg,
resample_linear,
stft,
time_stretch,
)
FS = 8000
def zero_crossing_freq(v, lo, hi):
"""The frequency from the rising zero crossings of v in [lo, hi)."""
c = [i for i in range(max(lo, 1), hi) if v[i - 1] < 0 <= v[i]]
return (len(c) - 1) / ((c[-1] - c[0]) / FS)
class TestPrincarg(unittest.TestCase):
def test_range_and_congruence(self):
rng = random.Random(1)
for _ in range(500):
a = rng.uniform(-100.0, 100.0)
p = princarg(a)
self.assertGreaterEqual(p, -math.pi)
self.assertLess(p, math.pi)
m = (a - p) / (2.0 * math.pi)
self.assertAlmostEqual(m, round(m), places=9)
def test_fixed_points(self):
for a in (0.0, 1.0, -3.0, 3.1):
self.assertAlmostEqual(princarg(a), a, places=12)
self.assertAlmostEqual(princarg(math.pi), -math.pi, places=12)
class TestTransforms(unittest.TestCase):
def test_ifft_inverts_fft(self):
rng = random.Random(2)
x = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(64)]
y = ifft(fft(x))
self.assertLess(max(abs(a - b) for a, b in zip(x, y)), 1e-12)
def test_hann_overlap_is_constant(self):
w = periodic_hann(64)
for i in range(16):
self.assertAlmostEqual(sum(w[i + 16 * j] for j in range(4)), 2.0, places=12)
class TestInstantaneousFrequency(unittest.TestCase):
def test_exact_for_complex_exponential(self):
# A complex exponential of any frequency: the estimate is exact for the bins near it.
n, hop = 256, 64
w = periodic_hann(n)
for f in (0.1, 0.2345, 0.31, 1.0):
x = [cmath.exp(1j * f * i) for i in range(n + hop)]
a = fft([x[i] * w[i] for i in range(n)])
b = fft([x[hop + i] * w[i] for i in range(n)])
k = round(f * n / (2.0 * math.pi))
for kk in (k - 1, k, k + 1):
self.assertAlmostEqual(instantaneous_frequency(a[kk], b[kk], kk, n, hop), f, places=9)
def test_page_example(self):
x = sine(440, FS, 4096, 0.5)
spectra = stft(x, 1024, 256, periodic_hann(1024))
om = instantaneous_frequency(spectra[0][56], spectra[1][56], 56, 1024, 256)
self.assertAlmostEqual(om * FS / (2 * math.pi), 440.0, places=4)
self.assertAlmostEqual(abs(spectra[1][56]), 119.767, places=2)
class TestStretch(unittest.TestCase):
def test_identity_when_hops_are_equal(self):
rng = random.Random(3)
x = [rng.uniform(-1, 1) for _ in range(3000)]
y = time_stretch(x, 1.0, 256, 64)
# Where the window sum is not small, the output equals the input.
self.assertLess(max(abs(a - b) for a, b in zip(x[256:2700], y[256:2700])), 1e-10)
def test_overlap_add_of_windowed_frames(self):
w = periodic_hann(16)
x = [float(i % 7) for i in range(64)]
fr = [[x[s + i] * w[i] for i in range(16)] for s in range(0, 49, 4)]
y = overlap_add(fr, 4, w)
for i in range(12, 52):
self.assertAlmostEqual(y[i], x[i], places=10)
def test_length(self):
x = sine(440, FS, 4096, 0.5)
for ratio in (0.75, 1.5, 2.0):
y = time_stretch(x, ratio)
hs = round(256 * ratio)
self.assertEqual(len(y), 12 * hs + 1024)
def test_stretched_sine_keeps_frequency(self):
x = sine(440, FS, 4096, 0.5)
y = time_stretch(x, 1.5)
self.assertEqual(len(y), 5632)
f = zero_crossing_freq(y, 1100, 4800)
self.assertLess(abs(f - 440.0) / 440.0, 0.005)
peak = max(abs(v) for v in y[1100:4800])
self.assertLess(abs(peak - 0.5), 0.05)
def test_pitch_shift(self):
x = sine(440, FS, 4096, 0.5)
y = pitch_shift(x, 1.25)
self.assertLess(abs(len(y) - 4096) / 4096, 0.06)
f = zero_crossing_freq(y, 1100, 3000)
self.assertLess(abs(f - 550.0) / 550.0, 0.005)
def test_resample_linear(self):
x = [float(i) for i in range(10)]
self.assertEqual(resample_linear(x, 2.0), [0.0, 2.0, 4.0, 6.0, 8.0])
self.assertEqual(resample_linear(x, 0.5)[:4], [0.0, 0.5, 1.0, 1.5])
def test_short_input(self):
self.assertEqual(time_stretch([0.0] * 100, 2.0), [])
if __name__ == "__main__":
unittest.main()
History
James Flanagan and Roger Golden of Bell Labs published the phase vocoder in 1966 for speech coding: each channel of a filter bank was sent as its magnitude and its phase derivative, the instantaneous frequency, which change slowly and need fewer bits than the wave. Michael Portnoff showed in 1976 how to compute it with the FFT, which made it practical, and it became a standard tool for time stretching and pitch shifting in computer music. Jean Laroche and Mark Dolson analyzed its phasiness in 1999 and proposed phase locking around spectral peaks, which most later implementations use.
References
- J. L. Flanagan and R. M. Golden, Phase Vocoder, Bell System Technical Journal 45(9), 1966, 1493 to 1509, the whole paper (the analysis into magnitude and phase derivative per channel, and the synthesis from them)
- M. R. Portnoff, Implementation of the digital phase vocoder using the fast Fourier transform, IEEE Transactions on Acoustics, Speech, and Signal Processing 24(3), 1976, 243 to 248, the whole paper (the phase vocoder computed with the FFT)
- J. Laroche and M. Dolson, Improved phase vocoder time-scale modification of audio, IEEE Transactions on Speech and Audio Processing 7(3), 1999, 323 to 332, the description of the standard phase vocoder, its phasiness, and the phase locking methods
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag M9RGV0 Edit this page History Report an error Markdown