Vocoders: turning acoustic descriptions into waveforms
声码器
Build a source-filter signal, derive the least-squares inverse STFT and test Griffin-Lim phase recovery.
vocoderThe spectrum is right. Is the sound the same?
Take a recorded waveform and multiply every sample by −1. Its short-time Fourier transform changes sign, but the magnitude of every coefficient remains the same. A magnitude plot cannot distinguish the two waveforms. This simple counterexample explains why generating acoustic features and generating waveform samples are separate problems.
In a TTS pipeline, a vocoder synthesizes a waveform from an acoustic description. That description might include pitch and filter parameters or a predicted spectrogram. It does not by itself specify every sample. A source-filter model supplies an excitation and shapes it with resonances; a phase-reconstruction method supplies phases compatible with a target magnitude. Learned waveform models make further modeling choices. These approaches solve different conditional reconstruction problems, so “vocoder” is not the name of a single algorithm.
The STFT article explains how a waveform becomes overlapping spectra. Here we ask which information is sufficient to reverse that operation, and what remains uncertain when phase has been discarded. Coleman’s source-filter account and Griffin–Lim’s reconstruction paper provide the two starting points. Source and filter Magnitude reconstruction
A sound source, a resonator and a missing phase
Over a locally stationary interval, model the source excitation as and the tract response as . A linear time-invariant approximation gives convolution in time and multiplication in frequency:
Periodic excitation contributes harmonic spacing related to fundamental frequency, or F0. Tract resonances shape the spectral envelope and are associated with formants. Periodic and noise excitation can coexist; the distinction is not simply “every sound is either a pure periodic signal or pure noise.” The model is an approximation: changing articulation and nonlinear interactions can violate the fixed-filter assumption. Source-filter account
Our synthetic filter cascades second-order resonators. For center frequency , bandwidth parameter and sample rate , choose poles and the recurrence:
Positive bandwidth makes , placing the poles inside the unit circle. The gain is a teaching choice. Harmonic excitation with F0=125 or 250 Hz passes through the same centers 700, 1100 and 2500 Hz at an 8 kHz sample rate. Changing F0 changes harmonic spacing without changing those poles. Each stage starts at zero, so the beginning contains a transient; the final waveform is peak-normalized and cannot be used to infer absolute loudness or physical gain.
Now define a reconstruction problem with explicit boundaries. The signal has length , the even frame length is , and hop divides both. Our frames wrap around the signal rather than use a library’s default padding. Full-frequency orthonormal FFT gives analysis operator :
For a real waveform, the complex spectrum has conjugate symmetry. Inverse FFT recovers a windowed frame. Multiplying it by the synthesis window creates a squared-window factor, so overlap-add must divide by accumulated squared windows:
The symbol now denotes the least-squares inverse operator, and its adjoint. To see why this is least squares, minimize the sum of squared discrepancies between each windowed output frame and the inverse-transformed supplied frame. Differentiating with respect to one sample gives a numerator summed with one window factor and a denominator summed with two. Dividing by the sum of windows instead would solve a different problem. With complete coverage, and projects arbitrary spectra onto the consistent-STFT subspace. Griffin and Lim derive the least-squares inverse; our circular boundary and sine window are explicit implementation choices. Equations 5–6
If only magnitude is supplied, the original no-momentum iteration alternates two operations. It replaces the current spectral magnitude while retaining phase, then reconstructs a consistent waveform:
Here is the number of spectral coefficients, and the zero-coefficient phase convention is 1. Magnitude replacement selects a nearest point among spectra with magnitude ; is an orthogonal projection. These two nearest-point properties imply:
Thus the magnitude objective is nonincreasing under this exact inverse, apart from roundoff. It does not imply convergence to the original phase or a unique global solution. The sign counterexample persists even with zero objective:
The fixed librosa implementation defaults to momentum 0.99 and has different initialization and boundary conventions. Its accelerated loop must not inherit the above plain alternating-projection guarantee without a separate argument. This program implements no momentum. Modern implementation
Generate a signal, discard phase, reconstruct
Run with Python 3.12 and NumPy 1.26.4. The source contains only generated harmonics and optionally seeded noise; there is no voice recording. The implementation checks real-signal conjugate symmetry, nonnegative magnitudes and finite arrays. Signal lengths are 16–2048; even windows are 8–256 and cannot exceed the signal; the hop must divide the window and signal and be at most half the window. The largest permitted magnitude is 32 and iteration count is 100.
The independent checks construct the entire real analysis matrix from basis impulses and compare the inverse with a least-squares solve. They also check projection idempotence, orthogonality, nonincreasing reconstruction loss, silence and invalid boundaries. These tests target the mathematical properties used above rather than whether a graph looks plausible.
"""Original source-filter and no-momentum Griffin-Lim teaching computation.
Circular boundaries and full orthonormal FFT are explicit teaching choices.
This makes the least-squares projection exact; it is not librosa's defaults.
Synthetic excitation only, no intelligible speech or quality benchmark.
"""
import json
import numpy as np
def real_array(value,ndim,bound=10000):
a=np.asarray(value)
if a.dtype.kind not in 'fiu' or a.ndim!=ndim or a.size==0 or a.size>262144 or not np.isfinite(a).all() or np.any((a < -bound)|(a > bound)):raise ValueError('Invalid bounded real array')
return a.astype(float)
def geometry(n,length,hop):
if any(type(v) is not int for v in (n,length,hop)) or not 16<=n<=2048 or not 8<=length<=min(n,256) or length%2 or not 1<=hop<=length//2 or n%hop or length%hop:raise ValueError('Use bounded circular frames with a dividing hop')
indices=(np.arange(0,n,hop)[:,None]+np.arange(length))%n
window=np.sin(np.pi*(np.arange(length)+.5)/length)
return indices,window
def stft(signal,length=32,hop=8):
x=real_array(signal,1);indices,w=geometry(len(x),length,hop)
return np.fft.fft(x[indices]*w,axis=1,norm='ortho')
def istft(spectrum,n,hop=8):
s=np.asarray(spectrum)
if s.dtype.kind not in 'fciu' or s.ndim!=2 or not np.isfinite(s).all() or s.size>262144:raise ValueError('Invalid spectrum')
indices,w=geometry(n,s.shape[1],hop)
if s.shape!=indices.shape or np.any(abs(s)>10000):raise ValueError('Spectrum shape/range mismatch')
if not np.allclose(s,np.conj(s[:,(-np.arange(s.shape[1]))%s.shape[1]]),atol=1e-10,rtol=1e-12):raise ValueError('A real signal requires conjugate symmetry')
frames=np.fft.ifft(s,axis=1,norm='ortho').real
out=np.zeros(n);den=np.zeros(n)
np.add.at(out,indices.ravel(),(frames*w).ravel())
np.add.at(den,indices.ravel(),np.broadcast_to(w*w,indices.shape).ravel())
return out/den
def reconstruct(magnitudes,n,hop=8,iterations=40,seed=3):
m=real_array(magnitudes,2,bound=32);indices,_=geometry(n,m.shape[1],hop)
if m.shape!=indices.shape or np.any(m<0) or not np.allclose(m,m[:,(-np.arange(m.shape[1]))%m.shape[1]],atol=1e-12,rtol=0):raise ValueError('Use nonnegative symmetric magnitudes')
if type(iterations) is not int or not 0<=iterations<=100 or type(seed) is not int or not 0<=seed<2**32:raise ValueError('Invalid iterations/seed')
x=np.random.default_rng(seed).normal(size=n);history=[]
for step in range(iterations+1):
s=stft(x,m.shape[1],hop);amplitude=abs(s)
history.append(float(np.mean((amplitude-m)**2)))
if step<iterations:
phase=np.divide(s,amplitude,out=np.ones_like(s),where=amplitude>0)
x=istft(m*phase,n,hop)
return dict(signal=x,history=history,spectrum=stft(x,m.shape[1],hop))
def source_filter(f0=125,fs=8000,n=512,formants=(700,1100,2500),bandwidths=(100,120,180),noise=0.,seed=0):
if type(fs) is not int or not 4000<=fs<=48000 or type(n) is not int or not 16<=n<=2048 or type(f0) not in (int,float) or not 40<=f0<fs/4 or type(noise) not in (int,float) or not 0<=noise<=1 or type(seed) is not int or not 0<=seed<2**32:raise ValueError('Invalid excitation settings')
f=real_array(formants,1,24000);b=real_array(bandwidths,1,1000)
if not 1<=len(f)<=6 or b.shape!=f.shape or np.any(f<=0) or np.any(f>=fs/2) or np.any(b<10):raise ValueError('Invalid resonances')
t=np.arange(n)/fs;harmonics=int(np.floor((fs/2-1)/f0))
excitation=sum(np.cos(2*np.pi*k*f0*t)/k for k in range(1,harmonics+1))
excitation/=np.max(abs(excitation));excitation=(1-noise)*excitation+noise*np.random.default_rng(seed).normal(0,.3,n)
y=excitation.copy();poles=[]
for center,width in zip(f,b):
radius=np.exp(-np.pi*width/fs);a=2*radius*np.cos(2*np.pi*center/fs);out=np.zeros(n)
for i in range(n):out[i]=(1-radius)*y[i]+(a*out[i-1] if i else 0)-(radius**2*out[i-2] if i>1 else 0)
y=out;poles.append(float(radius))
peak=float(np.max(abs(y)));y=y/peak if peak else y
return dict(signal=y,excitation=excitation,pole_radii=poles,raw_peak=peak,formants=f,f0=f0)
def demo():
low=source_filter();high=source_filter(f0=250);mixed=source_filter(noise=.5)
x=low['signal'];m=abs(stft(x));result=reconstruct(m,len(x));other=reconstruct(m,len(x),seed=8)
return dict(protocol=dict(n=512,fs=8000,length=32,hop=8,boundary='circular',iterations=40,momentum=0),
source_filter=dict(f0=[125,250],formants=low['formants'].tolist(),pole_radii=low['pole_radii'],peak_normalized=True,low=low['signal'].tolist(),high=high['signal'].tolist(),mixed=mixed['signal'].tolist()),
recovery=dict(history=result['history'],signal=result['signal'].tolist(),waveform_mse=float(np.mean((x-result['signal'])**2)),other_seed_mse=float(np.mean((x-other['signal'])**2)),sign_flipped_magnitude_error=float(np.max(abs(abs(stft(-x))-m)))),
roundtrip_error=float(np.max(abs(istft(stft(x),len(x))-x))))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
For the 512-sample signal,32-sample window and 8-sample hop,40 iterations reduce magnitude MSE from about 0.404261 to 0.00130450. The waveform MSE against the original is still about 0.157844; another seed gives about 0.131293. These quantities compare different objects with different normalizations and are not interchangeable quality scores. The complex-STFT roundtrip error is around machine precision, so the remaining phase uncertainty is not explained by an incorrect ordinary inverse.
The output stores computed waveforms and errors. We did not conduct a listening test or generate a WAV companion in this example. FFT computations can vary at the last few floating-point bits; comparisons use stated numerical tolerances, not byte equality.
One reconstruction iteration costs with spectral storage. The resonator cascade costs for resonators. Those small synthetic costs do not establish latency or quality of a full speech synthesizer.
Consistency is only one requirement
A magnitude predicted by an acoustic model need not be the magnitude of any exactly consistent STFT. In that case even the best reconstruction has nonzero residual. When the target is consistent, phase ambiguity still exists. A lower reconstruction objective answers a spectral-fitting question, not whether listeners understand the intended words.
The source-filter example holds resonances fixed, uses a short circular reconstruction domain and normalizes peaks. It therefore omits articulatory changes, unvoiced transitions and realistic loudness control. Its formant settings are parameters for a demonstration, not validated pronunciations of particular vowels.
For a practical comparison, keep sample rate, feature extraction and normalization fixed; check the acoustic model and vocoder agree on each. Evaluate the predicted acoustic features as well as the resulting waveform, then use a declared listening protocol for speech quality. Substituting an oracle spectrogram for a predicted one changes the task and should be reported explicitly.
Find the information that was lost
- Pitch versus resonance. Keep the three resonators unchanged and change F0 from 125 to 250 Hz. Which part of the model changes?
Answer: The excitation’s harmonic spacing changes. The filter poles and their center-frequency parameters stay fixed. The output spectrum can still change substantially because a different set of harmonics samples the same envelope.
- The overlap denominator. Why does the inverse divide by the sum of squared windows, rather than the sum of windows?
Answer: Analysis multiplies a sample by a window, and synthesis multiplies its recovered frame by a window again. Differentiating the frame least-squares error yields that same squared-window denominator. Changing it would generally destroy exact reconstruction for this analysis/synthesis pair.
- Perfect magnitude, wrong samples. If , what are the magnitude error and waveform MSE?
Answer: Magnitude error is zero in exact arithmetic, because a linear transform changes sign and absolute value removes that sign. Waveform MSE is four times the mean squared value of . Unless is silent, matching magnitudes therefore does not identify the original samples.
- An apparently better reconstruction. A developer adds momentum and observes one iteration with a higher objective. Does that refute the proof above?
Answer: No. The proof assumes two exact nearest-point operations with no momentum. An extrapolated update is a different iteration. Check its own assumptions and implementation rather than calling every Griffin-Lim variant identical or silently applying the plain-loop guarantee.
Separate the physical model from the optimization method
Coleman’s teaching page supports excitation and tract-resonance distinctions. Griffin and Lim’s 1984 paper supports least-squares STFT synthesis and the original iterative magnitude method. The fixed librosa code documents a later accelerated implementation. Our reading scope covers those mechanisms, not the paper’s full appendix, every experiment, or the page’s audio demonstrations.
For the next comparison, replace iterative phase estimation with a conditional learned waveform generator while holding the input acoustic representation fixed. That separates a modeling change from a change in the information supplied to the system.
Make a prediction, then check
Why does a tiny magnitude-spectrum error not prove recovery of the original waveform?
Learning objectives
- Distinguish excitation pitch from vocal-tract resonances.
- Derive squared-window normalization as a least-squares inverse.
- Explain Griffin-Lim monotonicity and phase nonuniqueness.
- Separate magnitude error from waveform error and listening quality.
Prerequisites & connections
Explore related knowledge →References
- The source-filter theory of speech production
John Coleman - Signal Estimation from Modified Short-Time Fourier Transform
Daniel W. Griffin; Jae S. Lim · 1984 - librosa Griffin-Lim implementation atf808bac
librosa contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked source-filter pitch/resonance distinctions, exact least-squares squared-window inverse, original no-momentum Griffin-Lim projection argument and phase ambiguity. Seven paired equations and four explained exercises; circular synthetic signals and stable resonators, no listening benchmark.
- Independent real analysis-matrix least-squares solve, projection idempotence/orthogonality, window coverage, silence and invalid boundaries tested. Forty-step magnitude loss0.404261 to0.00130450 does not recover original samples; sign ambiguity and seeds checked.
- Four computed SVGs bind exact bilingual MDX. The four-topic group passed14 numeric/encoding checks and24 isolated language/width cases with four fallback fonts; eight representative actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- The source-filter theory of speech production · Read extracted page text for periodic/noise excitation and vocal-tract resonances. Audio and embedded figures not inspected; demographic pitch ranges not adopted. Publication date unconfirmed.
- Signal Estimation from Modified Short-Time Fourier Transform · Read sectionII equations5–6 and sectionIII equations12–14; inspected printed pages237–238 (PDF2–3). Exact least-squares inverse and original no-momentum loop; appendix not fully read and experiments not reproduced.
- librosa Griffin-Lim implementation atf808bac · Read2671–2688 and2833–2924: defaults, random phase, momentum and inverse/forward loop. ISC license read; README only cached. No upstream execution or copied implementation.
Related topics