有很多方法可以做到这一点。最简单的方法是查看 Kernels 在 Kaggle 竞赛 TensorFlow Speech Recognition Challenge 中提出的方法(按投票最多的排序)。 This one 特别清晰简洁,包含以下功能。输入是从 wav 文件中提取的样本的数字向量、采样率、以毫秒为单位的帧大小、以毫秒为单位的步长(步幅或跳过)大小和一个小偏移量。
from scipy.io import wavfile
from scipy import signal
import numpy as np
sample_rate, audio = wavfile.read(path_to_wav_file)
def log_specgram(audio, sample_rate, window_size=20,
step_size=10, eps=1e-10):
nperseg = int(round(window_size * sample_rate / 1e3))
noverlap = int(round(step_size * sample_rate / 1e3))
freqs, times, spec = signal.spectrogram(audio,
fs=sample_rate,
window='hann',
nperseg=nperseg,
noverlap=noverlap,
detrend=False)
return freqs, times, np.log(spec.T.astype(np.float32) + eps)
输出在SciPy manual 中定义,但频谱图是用单调函数 (Log()) 重新调整的,它比较小的值更能抑制较大的值,同时使较大的值仍然大于较小的值价值观。这样,规格中的极值将不会主导计算。或者,可以将值限制在某个分位数,但首选对数(甚至平方根)。还有许多其他方法可以标准化频谱图的高度,即防止极端值“欺负”输出:)
freq (f) : ndarray, Array of sample frequencies.
times (t) : ndarray, Array of segment times.
spec (Sxx) : ndarray, Spectrogram of x. By default, the last axis of Sxx corresponds to the segment times.
或者,您可以从Tensorflow example on audio recognition 检查github repo 上的train.py 和models.py 代码。
Here is another thread 解释并提供有关在 Python 中构建频谱图的代码。