[英]How to plot spectrum or frequency vs amplitude of entire audio file using python?
通常,您使用librosa.display.specshow绘制一段时间内的频谱图,而不是整个文件。 实际上,根据您的分类目标,您可能宁愿使用由librosa.stft生成的频谱图或某些Mel频谱图作为CNN的输入。
例如,如果您要对类型进行分类,则梅尔谱图可能是最合适的。 如果您想找出琴键或和弦,则需要一个恒定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()
这将导致以下输出:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.