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()
通常使用librosa.display.specshow绘制随时间变化的光谱图,而不是整个文件。事实上,作为CNN的输入,您可能宁愿使用由librosa.stft生成的随时间变化的谱图或一些Mel谱图,这取决于您的分类目标是什么。在
例如,如果你想按体裁分类,Mel谱图可能是最合适的。如果你想找出琴键或和弦,你需要一个常量Q谱图(CQT),等等
也就是说,这里有一些代码可以回答您的问题:
这将导致以下输出:
相关问题 更多 >
编程相关推荐