STFT: windows, coverage and reconstructing a signal
短时傅里叶变换
Separate window length, hop and FFT length; reconstruct a complex STFT and expose missing coverage and phase.
stftTwo tones are present—but which came first?
Synthesize a short signal with a 500 Hz cosine in its first half and a 2 kHz cosine in its second. One Fourier transform of the full record describes frequency composition, but a global magnitude spectrum does not directly reveal when each sound occurred. The short-time Fourier transform (STFT) slides an analysis window through time and analyzes each local segment. STFT definition and parameters
Windows are not necessarily disjoint boxes. Adjacent windows usually overlap, and smooth sample weights reduce abrupt segment-edge effects while also broadening spectral main peaks. Short windows locate rapid changes more closely; long windows observe more time and can help distinguish nearby frequencies. No single window suits every transient and sustained tone.
We retain a complex STFT to reconstruct the signal, then deliberately lose coverage or phase to expose failure. Finally, we pad a 32-sample window to a 128-point FFT: the spectrum becomes denser without recording any more time.
Window length, hop and FFT length have different jobs
Suppose the record has real samples at rate . The window length is , successive windows start samples apart, and the FFT length is . We use an even-length periodic Hann window:
“Periodic” means the denominator is , not the of the symmetric Hann definition. Write the boundary-padded signal as . Frame begins at , with no extra forward-FFT normalization:
Conjugate symmetry recovers the negative frequencies of real signals, so we retain only nonnegative frequencies. Each complex value has magnitude and phase; magnitude or power plots display only part of the STFT. With samples padded on the left, midpoint time labels and frequency bins are:
At 8 kHz, and give 4 ms windows every 1 ms. A small hop does not supply independent 1 ms observations: overlapping windows share data. Edge windows also include artificial padding, making the time-label convention part of the specification.
Inverse FFT of a frame, cropped to its first samples, gives . Multiplying by the window again and adding frames accumulates each original sample times squared window weights. Divide by their corresponding sum:
Treat as zero outside its support. This is weighted overlap-add (OLA). Nonzero overlap-add (NOLA) requires a nonzero denominator at relevant positions, together with complete record coverage. The denominator need not be constant because the program divides pointwise. The Notes in the SciPy documentation give this denominator and the coverage conditions. Reconstruction and NOLA
Without padding, a first frame beginning at original sample 0 has Hann weight . The first input sample may never receive any nonzero weight. A longer FFT cannot fix this. Check padding and hop jointly on the actual finite record rather than declaring invertibility from the window’s name.
For an even FFT length, Parseval’s relation for an unnormalized one-sided complex spectrum is:
Interior bins receive factor 2 because each represents a positive/negative frequency pair. DC and Nyquist count once. This is the energy of one windowed frame; adding energies across overlapping frames does not directly produce the original record’s energy.
Zero padding has a separate direct check. Pad the same -sample windowed segment to points, and the original FFT values occur at every fourth new bin:
This samples the spectrum of the same finite window more densely, helping peak inspection and interpolation. It adds no independent samples or observation time. Julius O. Smith’s textbook explains padding through spectral interpolation; smaller grid spacing is not the same as increased ability to distinguish nearby components. Zero padding and interpolation
Reconstruction should expose missing information
The complete Python 3.12/NumPy 1.26.4 program accepts at most 1,024 samples, an even window length from 4 to 128 and an even FFT length no greater than 512. It does not detrend. Default padding adds samples on the left, then on the right plus enough to complete the hop grid. Output rows are frames; columns are nonnegative frequency bins.
"""Finite one-sided STFT and explicit weighted overlap-add reconstruction.
Raw unnormalized FFT, periodic Hann, even frame/FFT lengths, no detrending.
"""
import json
import numpy as np
def analyze(values,frame=32,hop=8,nfft=None,pad=True):
x=np.asarray(values)
if np.iscomplexobj(x):raise ValueError('Real signal required')
x=np.asarray(x,dtype=float);nfft=frame if nfft is None else nfft
if x.ndim!=1 or not 1<=len(x)<=1024 or not np.isfinite(x).all():raise ValueError('Use 1–1024 finite samples')
if type(frame) is not int or not 4<=frame<=128 or frame%2 or type(hop) is not int or not 1<=hop<=frame or type(nfft) is not int or not frame<=nfft<=512 or nfft%2 or type(pad) is not bool:raise ValueError('Invalid frame, hop, FFT or padding')
if not pad and len(x)<frame:raise ValueError('Unpadded signal needs a complete frame')
left=frame//2 if pad else 0;work=np.pad(x,(left,frame if pad else 0))
if pad:work=np.pad(work,(0,(-(len(work)-frame))%hop))
window=.5-.5*np.cos(2*np.pi*np.arange(frame)/frame);starts=np.arange(0,len(work)-frame+1,hop)
frames=np.array([work[i:i+frame]*window for i in starts]);spectrum=np.fft.rfft(frames,n=nfft,axis=1)
return dict(spectrum=spectrum,window=window,starts=starts,left=left,length=len(x),work_length=len(work),nfft=nfft,hop=hop)
def reconstruct(state):
z=state['spectrum'];w=state['window'];frames=np.fft.irfft(z,n=state['nfft'],axis=1)[:,:len(w)]
numerator=np.zeros(state['work_length']);denominator=numerator.copy()
for start,frame in zip(state['starts'],frames):
numerator[start:start+len(w)]+=frame*w;denominator[start:start+len(w)]+=w*w
sl=slice(state['left'],state['left']+state['length']);den=denominator[sl];num=numerator[sl];covered=den>1e-12
values=np.divide(num,den,out=np.zeros_like(num),where=covered)
return dict(values=values,denominator=den,covered=covered,exactly_invertible=bool(covered.all()))
def frame_energy(spectrum,nfft):
power=abs(spectrum)**2;weights=np.full(power.shape[-1],2.);weights[0]=weights[-1]=1
return np.sum(power*weights,axis=-1)/nfft
def demo():
rate=8000;n=128;t=np.arange(n)/rate;x=.7*np.cos(2*np.pi*np.where(np.arange(n)<64,500,2000)*t)+.1
state=analyze(x);back=reconstruct(state);raw=analyze(x,pad=False);lost=reconstruct(raw)
n0=32;segment=np.cos(2*np.pi*750*np.arange(n0)/rate)*(.5-.5*np.cos(2*np.pi*np.arange(n0)/n0));short=np.fft.rfft(segment);dense=np.fft.rfft(segment,n=128)
return dict(rate=rate,samples=x.tolist(),starts=state['starts'].tolist(),centers=((state['starts']+16-state['left'])/rate).tolist(),
frequencies=np.fft.rfftfreq(32,1/rate).tolist(),magnitude=abs(state['spectrum']).tolist(),
max_reconstruction_error=float(np.max(abs(back['values']-x))),denominator=back['denominator'].tolist(),
unpadded_missing=np.flatnonzero(~lost['covered']).tolist(),unpadded_first_input=float(x[0]),
frame_energies=frame_energy(state['spectrum'],32).tolist(),
zero_padding=dict(short_magnitude=abs(short).tolist(),dense_magnitude=abs(dense).tolist(),
old_bins_error=float(np.max(abs(short-dense[::4]))),short_spacing_hz=250.,dense_spacing_hz=62.5,window_samples=32))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The synthetic 128-sample signal switches from 500 Hz in its first 64 samples to 2 kHz in its last 64, with cosine amplitude 0.7 and DC offset 0.1. Default complex-spectrum reconstruction has maximum absolute error about . Without padding, the first input value 0.8 lacks coverage and receives covered=False. Filling that output position with 0 is a convention, not successful recovery.
reconstruct consumes internal state returned by analyze; frame_energy likewise assumes the even-FFT contract. They are not general validators for arbitrary external objects. Numerical coverage requires a denominator above . A very small denominator can amplify error even when mathematically nonzero.
A separate 32-sample segment padded to 128 points changes frequency spacing from 250 Hz to 62.5 Hz while observing only 4 ms. dense[::4] agrees with the original complex spectrum, not merely its magnitude. Multiplying [1,2,3,4] by [0,0.5,1,0.5] gives [0,1,3,2]; both the time-domain and one-sided spectral calculations give energy 14.
For frames, FFT computation takes , windowing and OLA take , complex spectra occupy , and reconstruction buffers occupy . Zero padding and denser frame placement have real computational costs.
Displaying a spectrum does not recover a sound
The complex STFTs of and are negatives of one another, but their magnitudes agree. Invertibility of the complete complex STFT with valid coverage therefore does not imply that a magnitude spectrogram uniquely determines a waveform. Arbitrarily editing time-frequency cells may also create a matrix inconsistent with any exact STFT. We reconstruct only an unmodified complex spectrum and do not estimate phase.
Choose window length with event duration and frequency separation in mind; choose hop with temporal sampling density, coverage and cost in mind. Speech models may further apply logarithms or Mel pooling. OLA cannot restore information discarded by those operations. The cited SciPy 1.15.3 stft documentation marks that interface as legacy and points to a newer interface. This article examines the mathematical conditions rather than recommending the older API as a new project’s default. Interface status and conditions
Make each parameter’s role testable
-
Understanding. At 8 kHz, what durations correspond to a 32-sample window and an 8-sample hop? Does a 1 ms hop mean each frame contains only 1 ms of data?
Answer: The window lasts 4 ms and the hop 1 ms. Each frame still uses 4 ms of data, with substantial overlap between neighbors.
-
Calculation. Apply the periodic Hann window [0,0.5,1,0.5] to [1,2,3,4]. What is the resulting energy, and why not simply add one-sided squared magnitudes?
Answer: The windowed segment [0,1,3,2] has energy 14. An unnormalized FFT requires division by its length, and interior one-sided bins must be doubled, unlike DC and Nyquist.
-
Counterexample. Without padding, the first input 0.8 receives only window weight 0. Can increasing the FFT from 32 to 128 recover it?
Answer: No. Window multiplication has already erased that value. Padding adds spectral samples without changing the coverage denominator. Window placement, boundaries or coverage must change.
-
Method choice. Two nearby frequencies are difficult to distinguish with a 32-sample window. Should a zero-padded 128-point FFT be called “four times the resolution”?
Answer: No. Grid spacing decreases by four, but observation time remains 4 ms. Padding helps read peak shapes; gaining more distinguishing information requires considering a longer observation window and its temporal-localization cost.
Normalization is part of the method
The prerequisite is the Fourier transform. The pinned SciPy documentation supports window, hop, boundary and OLA/NOLA definitions. The padding textbook supports the interpolation explanation. This program independently implements raw FFTs and actual denominators; its outputs were not matched to library scaling conventions. Reconstruction, energy and padding results belong to this example, not a library-compatibility or phase-recovery evaluation.
Make a prediction, then check
Does padding a 32-sample frame to a 128-point FFT fix a missing first sample?
Learning objectives
- Define frame times and bins under explicit padding.
- Derive the squared-window OLA denominator.
- Check one-sided Parseval energy and finite coverage.
- Distinguish denser FFT bins from more observation information.
Prerequisites & connections
Explore related knowledge →References
- SciPy 1.15.3: scipy.signal.stft
SciPy contributors · 2025 - Spectral Audio Signal Processing: Zero Padding in the Time Domain
Julius O. Smith III
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked periodic Hann definition, frame/time/frequency axes, raw one-sided FFT, weighted OLA squared-window denominator with finite coverage, Parseval factors and zero-padding interpolation against scoped SciPy1.15.3 Notes and SASP. Six paired equations and four explained exercises. Internal state/even-FFT contracts explicit; no phase retrieval or library scaling compatibility claim.
- Checked direct4-point DFT, padded reconstruction, missing first sample, actual coverage under hop changes, weighted one-sided energy14 and unchanged old complex bins after32→128 padding.
- Four computed SVGs bind exact bilingual MDX. The five-topic group passed eleven numeric/encoding checks and 30 isolated language/width cases with four fallback fonts; ten 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:
- SciPy 1.15.3: scipy.signal.stft · Read parameters, returns, Notes window/OLA equations and NOLA/coverage conditions. The interface is marked legacy. Our raw-FFT implementation checks actual finite denominators and is not a SciPy scaling compatibility test.
- Spectral Audio Signal Processing: Zero Padding in the Time Domain · Read frequency interpolation, Practical Zero Padding, equation3.45 and peak-interpolation excerpt. Used for the unchanged-observation-time distinction; publication year not verified and no book figures copied.
Related topics