如何使用 python 绘制整个音频文件的频谱或频率与幅度的关系图?

How to plot spectrum or frequency vs amplitude of entire audio file using python?

我有一些音频文件,我想使用 PYTHON(librosa 库)像 "audacity" 软件一样绘制音频文件的平均频谱。我可以看到他们正在绘制整个音频的平均频率与振幅图。

之后,我想应用 CNN 对两个 类 样本进行分类。寻找建议。

谢谢。

import matplotlib.pyplot as plt
from scipy import signal
from scipy.io import wavfile

sample_rate, samples = wavfile.read('h1.wav')
samples=samples[:,0]
frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate)

plt.imshow(spectrogram)
plt.pcolormesh(times, frequencies, spectrogram)

plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()

通常您会使用 librosa.display.specshow to plot spectrograms over time, not over the whole file. In fact, as input for your CNN you might rather use a spectrogram over time as produced by librosa.stft 或一些 Mel 频谱图,具体取决于您的分类目标。

例如,如果您想按流派分类,梅尔频谱图可能是最合适的。如果你想找出调或和弦,你将需要一个恒定 Q 谱图 (CQT) 等

也就是说,这里有一些代码可以回答您的问题:

import librosa
import numpy as np
import matplotlib.pyplot as plt


file = YOUR_FILE
# load the file
y, sr = librosa.load(file, sr=44100)
# short time fourier transform
# (n_fft and hop length determine frequency/time resolution)
n_fft = 2048
S = librosa.stft(y, n_fft=n_fft, hop_length=n_fft//2)
# convert to db
# (for your CNN you might want to skip this and rather ensure zero mean and unit variance)
D = librosa.amplitude_to_db(np.abs(S), ref=np.max)
# average over file
D_AVG = np.mean(D, axis=1)

plt.bar(np.arange(D_AVG.shape[0]), D_AVG)
x_ticks_positions = [n for n in range(0, n_fft // 2, n_fft // 16)]
x_ticks_labels = [str(sr / 2048 * n) + 'Hz' for n in x_ticks_positions]
plt.xticks(x_ticks_positions, x_ticks_labels)
plt.xlabel('Frequency')
plt.ylabel('dB')
plt.show()

这导致了这个输出: