04. STFT and spectrograms
The spectra of speech and music change over time: a vowel lasts 50 to 200 ms, a plosive burst a
few milliseconds. One DFT of a whole utterance (notebook 03) combines them into one spectrum. The
short-time Fourier transform (STFT) takes many short, overlapping DFTs instead, giving the
time-frequency representation (the spectrogram) used as input by most speech systems. This
notebook specifies exactly how audio_samples frames, windows, pads and inverts, and the
time-frequency trade-off that applies to every choice of parameters.
Learning outcomes. After working through this notebook you can
write the STFT as framing + windowing + DFT and predict the number of frames, bins and the time/frequency spacing of a spectrogram;
explain the time-frequency trade-off and choose a window length for a task;
invert an STFT exactly (weighted overlap-add) and state when that is possible (the NOLA and COLA conditions);
convert to decibels with an absolute floor, and contrast it with a floor set relative to the loudest value.
import librosa
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as ss
import audio_samples as aus
rng = np.random.default_rng(seed=2026)
F64 = np.dtype("float64")
WT = aus.WindowType
FS = 16_000
Concept
Frames. Choose a window length \(N\) (also the FFT size here) and a hop \(H\), both in samples. Frame \(m\) is the windowed block of \(N\) samples starting at \(mH - p\):
where \(x[n]\) is the signal (taken as 0 outside \(0 \le n < L\)), \(L\) its length in samples, \(w[n]\)
the analysis window, \(m\) the frame index and \(p\) the padding in samples. With centre=True the
library pads \(p = \lfloor N/2 \rfloor\) zeros at both ends, so frame \(m\) is centred on sample
\(mH\), i.e. time \(t_m = mH/f_s\) seconds.
Sizes. The number of frames and the spacings are
where \(M\) is the number of frames, \(\Delta f\) the bin spacing in Hz, \(\Delta t\) the frame period in seconds and \(f_s\) the sample rate in Hz. The result has \(\lfloor N/2\rfloor + 1\) rows (bins) and \(M\) columns (frames).
Time-frequency trade-off. A window of \(N\) samples lasts \(N/f_s\) seconds and has a main lobe a few bins wide (about \(2\Delta f = 2 f_s / N\) Hz at \(-6\) dB for Hann), so a longer window separates closer frequencies but spreads events in time over a longer interval. The product of the two resolutions is fixed, so one cannot be improved without degrading the other. The hop \(H\) only sets the frame rate; it does not improve resolution on either axis.
Inversion. The library’s istft uses weighted overlap-add (WOLA): each frame is inverse
transformed, multiplied by the window again and added, and the sum is divided by the summed
squared windows:
where \(y_m\) is the inverse DFT of frame \(m\). This is exact wherever the denominator is non-zero, for any window: the NOLA (nonzero overlap-add) condition, \(\sum_m w^2[n - mH] > 0\) for every \(n\). Plain overlap-add (no window on synthesis, no division) needs the stronger COLA (constant overlap-add) condition \(\sum_m w[n - mH] = \text{const}\).
Decibels. A power spectrogram \(P = |X_m[k]|^2\) is shown in dB as
where \(F\) is an absolute floor in dB (LogParams(floor_db=F)). A floor set at a fixed
distance below the loudest value (top_db) would instead move with the signal.
With the library
The test signal is two steady tones 40 Hz apart (1000 and 1040 Hz, like two close harmonics) plus a click at \(t = 0.5\) s (like a plosive burst), 1 s at 16 kHz.
t = np.arange(FS) / FS
x = 0.5 * np.sin(2 * np.pi * 1000 * t) + 0.5 * np.sin(2 * np.pi * 1040 * t)
x[8000] += 1.0
audio = aus.AudioSamples.new_mono(x, sample_rate=FS)
params = aus.StftParams(n_fft=512, hop_size=128, window=WT.hanning, centre=True)
res = audio.stft(params)
X = res.data # complex, shape (bins, frames)
print(params, X.shape, X.dtype)
assert X.shape == (257, 126) # 512/2 + 1 bins; 1 + floor(16000/128) frames
assert res.n_bins == 257 and res.n_frames == 126
assert res.frequency_resolution == 31.25 # Hz
assert abs(res.time_resolution - 0.008) < 1e-15 # s
assert np.allclose(res.frequencies, np.arange(257) * 31.25)
StftParams(n_fft=512, hop_size=128, window=Hanning, centre=true) (257, 126) complex128
The STFT bins are ordinary DFT bins, so a spectrogram is \(|X|^2\). The bundled spectrograms module
computes it directly (compute_linear_power_spectrogram, ..._magnitude_..., ..._db_...,
taking a NumPy array and SpectrogramParams):
sp = aus.SpectrogramParams(params, sample_rate=float(FS))
power = aus.spectrograms.compute_linear_power_spectrogram(x, sp)
assert np.allclose(power.data, np.abs(X) ** 2, rtol=1e-12, atol=0)
assert np.allclose(power.times, np.arange(126) * 0.008) # centred frames: t_m = m H / fs
db = aus.spectrograms.compute_linear_db_spectrogram(x, sp, aus.LogParams(-100.0)).data
assert db.min() == -100.0 # the absolute floor
print(f"dB range: {db.min():.1f} .. {db.max():.1f}")
fig, ax = plt.subplots(figsize=(8, 3))
im = ax.pcolormesh(power.times, np.asarray(power.frequencies) / 1000, db, shading="nearest", cmap="magma")
ax.set(xlabel="Time (s)", ylabel="Frequency (kHz)", title="N = 512, H = 128, Hann (power, dB)")
fig.colorbar(im, ax=ax, label="dB")
plt.show()
dB range: -100.0 .. 39.3
Because the reference is 1 (not the loudest bin), dB values are absolute and can be well above 0 dB. A full-scale 1 kHz sine is bin-centred for \(N = 512\) at 16 kHz (bin 32), so its peak power is \((\sum w / 2)^2\) and its level is \(20\log_{10}(255.5/2) = 42.13\) dB re 1. Silence is exactly at the floor, regardless of the rest of the file. Without centring the same 1 s signal gives 122 frames instead of 126.
sine = aus.sine_wave(1000.0, 0.5, sample_rate=FS, amplitude=1.0, dtype=F64)
floor = aus.LogParams(-80.0)
lin = aus.spectrograms.compute_linear_db_spectrogram(sine.to_numpy(), sp, floor).data
assert abs(WT.make_hanning(512).sum() - 255.5) < 1e-9 # (N - 1) / 2
assert abs(lin.max() - 20 * np.log10(255.5 / 2)) < 0.01 and abs(lin.max() - 42.13) < 0.01
quiet = aus.spectrograms.compute_linear_db_spectrogram(np.zeros(4000), sp, floor).data
assert np.all(np.abs(quiet + 80.0) < 1e-9)
no_centre = aus.StftParams(n_fft=512, hop_size=128, window=WT.hanning, centre=False)
assert audio.stft(no_centre).n_frames == 122 == 1 + (16_000 - 512) // 128
At \(N = 512\) the two tones (40 Hz apart, a bit more than one bin) merge into one band, and the click is a short vertical line. Sweep \(N\) (with \(H = N/4\)) and measure both: how many peaks appear between 900 and 1150 Hz in a frame far from the click, and how long the click’s high-frequency energy (above 4 kHz, where the tones contribute nothing) stays within 6 dB of its peak.
def tf_tradeoff(n):
hop = n // 4
r = audio.stft(aus.StftParams(n_fft=n, hop_size=hop, window=WT.hanning, centre=True))
p = np.abs(r.data) ** 2
f = np.arange(r.n_bins) * FS / n
high = p[f >= 4000].sum(axis=0)
click_ms = (high > high.max() * 10 ** (-6 / 10)).sum() * hop / FS * 1000
m = np.sqrt(p[:, r.n_frames // 4]) # a frame around t = 0.25 s
idx = np.where((f > 900) & (f < 1150))[0]
top = m[idx].max()
peaks = sum(1 for i in idx if m[i] > m[i - 1] and m[i] >= m[i + 1] and m[i] > 0.5 * top)
return peaks, click_ms
table = {n: tf_tradeoff(n) for n in [128, 256, 512, 1024, 2048]}
for n, (peaks, click_ms) in table.items():
print(f"N = {n:4d} ({1000 * n / FS:5.1f} ms, bins {FS / n:6.2f} Hz): {peaks} peak(s), click {click_ms:4.0f} ms")
# The click stays within 6 dB for half a window, N / (2 fs): 4 ms at N = 128, 64 ms at N = 2048.
assert all(click_ms == 1000 * n / (2 * FS) for n, (_, click_ms) in table.items())
# Two tones 40 Hz apart need a Hann main lobe 2 fs / N <= 40 Hz, i.e. N >= 800: resolved from 1024.
assert [table[n][0] for n in [128, 256, 512]] == [1, 1, 1]
assert [table[n][0] for n in [1024, 2048]] == [2, 2]
N = 128 ( 8.0 ms, bins 125.00 Hz): 1 peak(s), click 4 ms
N = 256 ( 16.0 ms, bins 62.50 Hz): 1 peak(s), click 8 ms
N = 512 ( 32.0 ms, bins 31.25 Hz): 1 peak(s), click 16 ms
N = 1024 ( 64.0 ms, bins 15.62 Hz): 2 peak(s), click 32 ms
N = 2048 (128.0 ms, bins 7.81 Hz): 2 peak(s), click 64 ms
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)
for ax, n in zip(axes, [128, 2048]):
spn = aus.SpectrogramParams(aus.StftParams(n_fft=n, hop_size=n // 4, window=WT.hanning, centre=True), sample_rate=float(FS))
s = aus.spectrograms.compute_linear_db_spectrogram(x, spn, aus.LogParams(-100.0))
ax.pcolormesh(s.times, np.asarray(s.frequencies), s.data, shading="nearest", cmap="magma")
ax.set(xlabel="Time (s)", title=f"N = {n} ({1000 * n / FS:.0f} ms)", ylim=(500, 1500), xlim=(0.35, 0.65))
axes[0].set_ylabel("Frequency (Hz)")
fig.tight_layout()
plt.show()
With a short window the click is narrow in time and the two tones form one band. With a long window the two tones are separate and the click is spread in time.
Inversion. istft reconstructs the signal to rounding error. Its output has
\((M - 1)H\) samples, so with centre=True the last \(L \bmod H\) samples are not returned; pad the
input to a multiple of \(H\) if you need them all.
y = audio.istft(res).to_numpy()
L, H = audio.samples_per_channel(), params.hop_size
print(len(y), (res.n_frames - 1) * H)
assert len(y) == (res.n_frames - 1) * H == (L // H) * H # 16000 is a multiple of 128: nothing lost
# WOLA divides by the summed squared windows: exact to rounding (values of size ~1).
assert np.allclose(y, x[: len(y)], atol=1e-12)
# A length that is not a multiple of the hop: 4000 samples, H = 256 -> 3840 returned.
short = aus.AudioSamples.new_mono(rng.standard_normal(4000) * 0.1, sample_rate=FS)
p256 = aus.StftParams(n_fft=512, hop_size=256, window=WT.hanning, centre=True)
y_short = short.istft(short.stft(p256)).to_numpy()
assert len(y_short) == 3840 and np.allclose(y_short, short.to_numpy()[:3840], atol=1e-12)
16000 16000
How it works
Reimplement the STFT with NumPy: pad \(\lfloor N/2 \rfloor\) zeros, cut frames every \(H\) samples,
multiply by SciPy’s symmetric Hann (hann(N, sym=True)) and take np.fft.rfft. Then check
against librosa as an independent reference, with its conventions switched to match (symmetric
window passed explicitly, pad_mode="constant").
def my_stft(x, n, hop, window):
p = n // 2
xp = np.concatenate([np.zeros(p), x, np.zeros(p)])
m = (len(xp) - n) // hop + 1
frames = np.stack([xp[i * hop: i * hop + n] for i in range(m)], axis=1) # (n, M)
return np.fft.rfft(frames * window[:, None], axis=0)
w = ss.windows.hann(512, sym=True)
mine = my_stft(x, 512, 128, w)
# Each bin is a 512-term sum of values of size ~1: rounding of order 1e-13.
assert mine.shape == X.shape and np.allclose(mine, X, atol=1e-10)
ref = librosa.stft(x, n_fft=512, hop_length=128, window=w, center=True, pad_mode="constant")
assert np.allclose(ref, X, atol=1e-10)
# With a periodic Hann window the numbers differ; the padding (zeros) is the same, so the whole
# difference comes from the window:
import inspect
assert inspect.signature(librosa.stft).parameters["pad_mode"].default == "constant"
ref_default = librosa.stft(x, n_fft=512, hop_length=128)
periodic_hann = ss.get_window("hann", 512)
assert np.allclose(ref_default, librosa.stft(x, n_fft=512, hop_length=128, window=periodic_hann,
pad_mode="constant"), atol=1e-12)
assert np.allclose(my_stft(x, 512, 128, periodic_hann), ref_default, atol=1e-10)
print(f"max |library - librosa default| = {np.max(np.abs(ref_default - X)):.3f}")
assert not np.allclose(ref_default, X, atol=1e-3)
# The frame-count formula, for a few lengths and both centring modes.
for L_, n, hop, centre in [(16000, 512, 128, True), (16000, 400, 160, True), (4000, 512, 128, False), (1000, 256, 100, True)]:
sig = aus.AudioSamples.new_mono(np.ones(L_), sample_rate=FS)
r = sig.stft(aus.StftParams(n_fft=n, hop_size=hop, window=WT.hanning, centre=centre))
p = n // 2 if centre else 0
assert r.n_frames == (L_ + 2 * p - n) // hop + 1
max |library - librosa default| = 0.348
Inversion by weighted overlap-add, written out:
def my_istft(X, n, hop, window):
m = X.shape[1]
frames = np.fft.irfft(X, n=n, axis=0) * window[:, None]
out = np.zeros(n + hop * (m - 1))
norm = np.zeros_like(out)
for i in range(m):
out[i * hop: i * hop + n] += frames[:, i]
norm[i * hop: i * hop + n] += window ** 2
p = n // 2
return (out / np.where(norm > 1e-10, norm, 1.0))[p: len(out) - p]
y_mine = my_istft(X, 512, 128, w)
assert len(y_mine) == len(y) and np.allclose(y_mine, y, atol=1e-12)
Measuring COLA: the periodic Hann at 50 % overlap sums to exactly 1; the library’s
symmetric Hann deviates from 1 by a fraction of a percent. This does not affect istft (WOLA
divides it out) but it does affect plain overlap-add.
def ola_sum(window, hop, n_frames=16):
n = len(window)
s = np.zeros(n + hop * (n_frames - 1))
for i in range(n_frames):
s[i * hop: i * hop + n] += window
return s[n: -n] # steady-state part only
periodic = ss.get_window("hann", 512) # denominator N
sym = WT.make_hanning(512) # denominator N - 1
s_per, s_sym = ola_sum(periodic, 256), ola_sum(sym, 256)
ripple_sym = (s_sym.max() - s_sym.min()) / s_sym.mean()
print(f"periodic Hann, H = N/2: {s_per.min():.6f} .. {s_per.max():.6f}")
print(f"symmetric Hann, H = N/2: {s_sym.min():.6f} .. {s_sym.max():.6f}, ripple {100 * ripple_sym:.3f} %")
assert np.allclose(s_per, 1.0, atol=1e-12)
assert abs(100 * ripple_sym - 0.307) < 0.001
periodic Hann, H = N/2: 1.000000 .. 1.000000
symmetric Hann, H = N/2: 0.996926 .. 0.999991, ripple 0.307 %
Decibels with an absolute floor, against librosa. librosa.power_to_db(P, ref=1.0, amin=1e-10, top_db=None) is \(10\log_{10}\max(P, 10^{-10})\), i.e. the same formula with a \(-100\) dB floor;
with top_db=80 the floor is instead 80 dB below the loudest bin.
P = np.abs(X) ** 2
lib_db = aus.spectrograms.compute_linear_db_spectrogram(x, sp, aus.LogParams(-100.0)).data
assert np.allclose(lib_db, np.maximum(10 * np.log10(np.maximum(P, 1e-300)), -100.0), atol=1e-9)
assert np.allclose(lib_db, librosa.power_to_db(P, ref=1.0, amin=1e-10, top_db=None), atol=1e-9)
top = librosa.power_to_db(P, ref=1.0) # top_db = 80 by default
print(f"library floor: {lib_db.min():.1f} dB (fixed); librosa top_db floor: {top.min():.1f} dB = max - 80")
assert abs(top.min() - (top.max() - 80.0)) < 1e-9
library floor: -100.0 dB (fixed); librosa top_db floor: -40.7 dB = max - 80
Ask the library to explain
aus.explain.explain(params, ...) (or audio.explain(params), which takes the sample rate and
length from the signal) computes the sizes, spacings, overlap and the COLA/NOLA figures, and warns
about problems such as a window too short for the lowest expected pitch.
doc = audio.explain(params, f0_range=(80.0, 300.0))
assert doc.quantity("Frequency bins") == 257
assert doc.quantity("Frequency resolution") == res.frequency_resolution == 31.25 # Hz
assert doc.quantity("Frame period") == 8.0 # ms
assert doc.quantity("Window duration") == 32.0 # ms
assert doc.quantity("Overlap") == 75.0 # %
assert doc.quantity("Frames") == res.n_frames
assert not doc.has_warning("caution") # 32 ms >= two periods of 80 Hz (25 ms)
assert doc.quantity("Overlap-add ripple") > 0 and doc.has_warning_containing("constant-overlap-add")
doc
Short-time Fourier transform (STFT)
Frames of 512 samples (Hann window) every 128 samples (75% overlap), centred by padding ⌊N/2⌋ zeros at both ends. Each frame gives 257 frequency bins spaced 31.25 Hz apart, one frame every 8 ms.
Formulas
Frame m: window N samples starting at mH - p and take an N-point DFT (samples outside the signal are 0):
$$ X_m[k] = \sum_{n=0}^{N-1} x[mH + n - p] , w[n] , e^{-j \frac{2\pi}{N} k n} $$
Number of frames for L samples (at least 1):
$$ M = \left\lfloor \frac{L + 2p - N}{H} \right\rfloor + 1 $$
Bin spacing and frame period:
$$ \Delta f = \frac{f_s}{N}, \quad \Delta t = \frac{H}{f_s} $$
Inverse STFT as implemented (weighted overlap-add): exact wherever the denominator is non-zero (NOLA):
$$ \hat{x}[n] = \frac{\sum_m w[n - mH] , y_m[n - mH]}{\sum_m w^2[n - mH]} $$
Symbols
| Symbol | Meaning | Value | |—|—|—| | $N$ | FFT and window length | 512 samples | | $H$ | hop size | 128 samples | | $p$ | padding (centre = true): ⌊N/2⌋ zeros each side | 256 samples | | $w[n]$ | analysis window | Hann | | $m$ | frame index; frame m is time-stamped t_m = mH/f_s (its centre when centre = true, its start otherwise) | | | $L$ | signal length in samples | | | $f_s$ | sample rate | 16000 Hz |
Derived quantities
| Quantity | Value | Formula | |—|—|—| | Frequency bins | $\lfloor N/2 \rfloor + 1$ = 257 | $\lfloor N/2 \rfloor + 1$ | | Overlap | $1 - H/N$ = 75 % | $100 (1 - H/N)$ | | Frequency resolution | $\Delta f$ = 31.25 Hz | $f_s / N$ | | Frame period | $\Delta t$ = 8 ms | $1000 H / f_s$ | | Window duration | $N / f_s$ = 32 ms | $1000 N / f_s$ | | Frame rate | $f_s / H$ = 125 frames/s | $f_s / H$ | | Effective noise bandwidth | $\mathrm{ENBW},\Delta f$ = 46.9667 Hz | $\mathrm{ENBW} \cdot f_s / N$ | | Main-lobe width (-6 dB) | $B_6 \Delta f$ = 62.6199 Hz | $B_6 \cdot f_s / N$ | | Frames | $M$ = 126 | $\lfloor (L + 2p - N)/H \rfloor + 1$ | | Output size (values) | $M(\lfloor N/2 \rfloor + 1)$ = 32382 complex values | $M (\lfloor N/2 \rfloor + 1)$ | | Overlap-add gain | $C_{OLA}$ = 1.99609 | $\mathrm{mean}n \sum_m w[n - mH]$ | | Overlap-add ripple | $\mathrm{COLA}$ = 6.2979e-4 | $\frac{\max - \min}{\mathrm{mean}} \sum_m w[n - mH]$ | | Minimum squared-window sum | $\min_n \sum_m w^2[n-mH]$ = 1.49693 | $\min_n \sum_m w^2[n - mH]$ | | Overlap-add ripple of the periodic form | $\mathrm{COLA}{per}$ = 4.4409e-16 | $\text{same, for the periodic window (length } N+1 \text{, last sample dropped)}$ |
Trade-offs
A longer window sharpens frequency resolution (Δf = f_s/N) but lowers time resolution; the two cannot both be improved (time-frequency uncertainty).
A smaller hop gives smoother tracks over time at proportionally more computation; it does not improve frequency resolution.
The window shape trades main-lobe width (resolution) against side-lobe level (leakage); see the window explanation.
Warnings
Info: The window/hop pair is not constant-overlap-add: the summed windows ripple by 0.0629788% around their mean. The ripple comes entirely from the window being symmetric (denominator N-1): the periodic (DFT-even) Hann window at the same hop is exactly COLA (ripple 4.4409e-16). Hint: Plain overlap-add would modulate the amplitude; this crate’s istft divides by the summed squared windows, so reconstruction stays exact where NOLA holds.
See also
Forward transform:
audio_samples::AudioTransforms::stftForward transform (Python):
audio_samples.AudioSamples.stftInverse transform:
audio_samples::AudioTransforms::istftInverse transform (Python):
audio_samples.AudioSamples.istftWindow figures:
audio_samples::educational::topics::windowWindow figures (Python):
audio_samples.explain.windowPython:
audio_samples.explain.explain(StftParams)
# A 16 ms window is too short for an 80 Hz voice: two periods take 25 ms.
short_doc = aus.explain.explain(aus.StftParams(n_fft=256, hop_size=64, window=WT.hanning),
sample_rate=16_000.0, f0_range=(80.0, 300.0))
assert short_doc.has_warning("caution")
for w_ in short_doc.warnings:
print(f"[{w_['level']}] {w_['message']}\n hint: {w_['hint']}")
[info] The window/hop pair is not constant-overlap-add: the summed windows ripple by 0.124814% around their mean. The ripple comes entirely from the window being symmetric (denominator N-1): the periodic (DFT-even) Hann window at the same hop is exactly COLA (ripple 4.4409e-16).
hint: Plain overlap-add would modulate the amplitude; this crate's istft divides by the summed squared windows, so reconstruction stays exact where NOLA holds.
[caution] The window (16 ms) is shorter than two periods of the lowest expected f0 (80 Hz needs 25 ms), so its harmonics will not form clear peaks.
hint: Use N ≥ 400 samples at this sample rate.
Exercises
How many frames does
stftproduce for 2.5 s of audio at 22.05 kHz with \(N = 2048\), \(H = 512\) andcentre=True? Predict, then check.
answer = None # TODO
# Solution
L_ = int(2.5 * 22_050) # 55 125 samples
answer = 1 + (L_ + 2 * 1024 - 2048) // 512 # 1 + 107
assert answer == 108
clip = aus.sine_wave(440.0, 2.5, sample_rate=22_050, amplitude=0.5, dtype=F64)
assert clip.samples_per_channel() == L_
assert clip.stft(aus.StftParams(n_fft=2048, hop_size=512, window=WT.hanning, centre=True)).n_frames == answer
You want one frame every 10 ms and a bin spacing \(\Delta f = f_s/N\) of at most 20 Hz at 16 kHz (the spacing of the bins, not the main-lobe resolution of about \(2\Delta f\)). Choose \(H\) and the smallest power-of-two \(N\) (store
answer = (H, N)), and confirm with the explainer.
answer = None # TODO
# Solution
h = round(0.010 * 16_000) # 160
n = 1 << int(np.ceil(np.log2(16_000 / 20))) # N >= 800 -> 1024
answer = (h, n)
assert answer == (160, 1024)
d = aus.explain.explain(aus.StftParams(n_fft=n, hop_size=h, window=WT.hanning), sample_rate=16_000.0)
assert d.quantity("Frame period") == 10.0 and d.quantity("Frequency resolution") == 15.625
A signal is 0.5 s of a full-scale 1 kHz sine followed by 0.5 s of silence. With
LogParams(-100.0), what value (dB) do the bins of the last frame take, and how far below the spectrogram’s peak is that? (The second number is what a peak-referenced conversion such aslibrosa.power_to_db(P, ref=np.max, top_db=None)reports; withtop_db=80it is clipped to \(-80\) dB.)
answer = None # TODO
# Solution
v = np.concatenate([sine.to_numpy(), np.zeros(8000)])
s = aus.spectrograms.compute_linear_db_spectrogram(v, sp, aus.LogParams(-100.0)).data
answer = (-100.0, 100.0 + 42.13) # -100 dB re 1, 142.13 dB below the peak
assert np.all(np.abs(s[:, -1] - answer[0]) < 1e-9)
assert abs((s.max() - s[0, -1]) - answer[1]) < 0.01
# Peak-referenced: only with top_db=None (and amin = 1e-10, i.e. the same -100 dB floor) is it 142.13 dB.
P_v = aus.spectrograms.compute_linear_power_spectrogram(v, sp).data
assert np.allclose(librosa.power_to_db(P_v, ref=np.max, top_db=None, amin=1e-10)[:, -1], -answer[1], atol=0.01)
assert np.allclose(librosa.power_to_db(P_v, ref=np.max)[:, -1], -80.0) # top_db = 80 clips
A 4000-sample clip is analysed with \(N = 512\), \(H = 256\),
centre=Trueand inverted withistft. How many samples come back? How many zeros must you append to the clip so that all 4000 original samples are returned?
answer = None # TODO
# Solution
returned = (4000 // 256) * 256 # (M - 1) H with M = 1 + 4000 // 256
answer = (returned, (-4000) % 256) # (3840 samples, 96 zeros -> 4096 = 16 H)
assert answer == (3840, 96)
clip = rng.standard_normal(4000) * 0.1
padded = aus.AudioSamples.new_mono(np.concatenate([clip, np.zeros(answer[1])]), sample_rate=FS)
back = padded.istft(padded.stft(p256)).to_numpy()
assert len(back) == 4096 and np.allclose(back[:4000], clip, atol=1e-12)
Common pitfalls
centre=Truepads with zeros. An STFT that pads by reflection gives different edge frames.WindowType.hanningis the symmetric Hann. For the periodic one (as returned byscipy.signal.get_window("hann", N)), passWindowType.custom(scipy.signal.get_window("hann", N)).StftResult.datais a property (no parentheses), shaped(bins, frames).istftreturns \((M-1)H\) samples: pad the input to a multiple of the hop to get every sample back.dB conversion uses an absolute floor (
LogParams(floor_db)), not one relative to the loudest value. Always pass aLogParamsto the*_db_*functions.The hop does not improve resolution in either axis; only \(N\) (and the window shape) does.
See also
Rust guide chapter: 04. STFT and spectrograms (available from the next release; until then build the docs locally with
cargo doc --features educational,full_no_plotting --open) and the labexamples/tutorial_04_stft_spectrograms.rs.Python API:
AudioSamples.stft,AudioSamples.istft,StftParams,StftResult,SpectrogramParams,LogParams,audio_samples.spectrograms.compute_linear_db_spectrogram,aus.explain.explain(API reference).Previous: 03. The DFT, windows and leakage. Next: 05. Convolution and FIR filters. Mel spectrograms and MFCCs: 10. Cepstrum, mel and MFCC.
References
Allen, J. B. and Rabiner, L. R. (1977). A unified approach to short-time Fourier analysis and synthesis. Proceedings of the IEEE, 65(11), 1558-1564.
Griffin, D. W. and Lim, J. S. (1984). Signal estimation from modified short-time Fourier transform. IEEE Transactions on Acoustics, Speech, and Signal Processing, 32(2), 236-243. (The weighted overlap-add inverse used by
istft.)Harris, F. J. (1978). On the use of windows for harmonic analysis with the discrete Fourier transform. Proceedings of the IEEE, 66(1), 51-83.