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

2024-04-24 15:14:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些音频文件,我想用PYTHON(librosa库)绘制音频文件的平均频谱,比如“audacity”软件。我可以看到他们正在绘制整个音频的平均频率和振幅曲线图。在

enter image description here

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

谢谢。在


Tags: 软件绘制分类音频cnn建议音频文件频谱
2条回答

通常使用librosa.display.specshow绘制随时间变化的光谱图,而不是整个文件。事实上,作为CNN的输入,您可能宁愿使用由librosa.stft生成的随时间变化的谱图或一些Mel谱图,这取决于您的分类目标是什么。在

例如,如果你想按体裁分类,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()

这将导致以下输出:

dB for Frequencies

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()

相关问题 更多 >