使用具有重叠窗口的 STFT 来估计频谱图。为了省去自己滚动的麻烦,您可以使用 Matplotlib 的 mlab 的specgram method。重要的是使用足够小的窗口以使音频大致静止,并且缓冲区大小应该是 2 的幂,以有效地使用常见的 radix-2 fft。 512 个样本(48 ksps 时约 10.67 ms;或每个 bin 93.75 Hz)就足够了。对于 48 ksps 的采样率,重叠 464 个样本以每 1 ms 评估一个滑动窗口(即移动 48 个样本)。
编辑:
这是一个在 8 秒信号上使用 mlab.specgram 的示例,该信号在 2 kHz 到 16 kHz 范围内每秒发出 1 个音调。注意瞬态的响应。我放大了 4 秒以更详细地显示响应。频率偏移精确到 4 秒,但它需要一个缓冲长度(512 个样本;大约 +/- 5 毫秒)才能使瞬态通过。这说明了当它们通过缓冲区时由非平稳过渡引起的光谱/时间拖尾。此外,您可以看到即使信号是静止的,也会存在由数据窗口化引起的频谱泄漏问题。 Hamming window function 用于最小化泄漏的旁瓣,但这也扩大了主瓣。
import numpy as np
from matplotlib import mlab, pyplot
#Python 2.x:
#from __future__ import division
Fs = 48000
N = 512
f = np.arange(1, 9) * 2000
t = np.arange(8 * Fs) / Fs
x = np.empty(t.shape)
for i in range(8):
x[i*Fs:(i+1)*Fs] = np.cos(2*np.pi * f[i] * t[i*Fs:(i+1)*Fs])
w = np.hamming(N)
ov = N - Fs // 1000 # e.g. 512 - 48000 // 1000 == 464
Pxx, freqs, bins = mlab.specgram(x, NFFT=N, Fs=Fs, window=w,
noverlap=ov)
#plot the spectrogram in dB
Pxx_dB = np.log10(Pxx)
pyplot.subplots_adjust(hspace=0.4)
pyplot.subplot(211)
ex1 = bins[0], bins[-1], freqs[0], freqs[-1]
pyplot.imshow(np.flipud(Pxx_dB), extent=ex1)
pyplot.axis('auto')
pyplot.axis(ex1)
pyplot.xlabel('time (s)')
pyplot.ylabel('freq (Hz)')
#zoom in at t=4s to show transient
pyplot.subplot(212)
n1, n2 = int(3.991/8*len(bins)), int(4.009/8*len(bins))
ex2 = bins[n1], bins[n2], freqs[0], freqs[-1]
pyplot.imshow(np.flipud(Pxx_dB[:,n1:n2]), extent=ex2)
pyplot.axis('auto')
pyplot.axis(ex2)
pyplot.xlabel('time (s)')
pyplot.ylabel('freq (Hz)')
pyplot.show()