librosa melspectrogram y 轴刻度错误?

问题描述

我想弄清楚为什么梅尔标度频谱图似乎有错误的频率标度。我生成一个 4096Hz 的音调并使用 librosa 的显示库绘制它,但音调与已知频率不一致?我显然做错了什么,有人可以帮忙吗?谢谢!

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

sr = 44100
t = np.linspace(0,1,sr)
y = 0.1 * np.sin(2 * np.pi * 4096 * t)

M = librosa.feature.melspectrogram(y=y,sr=sr)
M_db = librosa.power_to_db(M,ref=np.max)
librosa.display.specshow(M_db,y_axis='mel',x_axis='time')
plt.show()

解决方法

当您使用 librosa.feature.melspectrogram(y=y,sr=sr) 计算梅尔频谱图时,您使用参数 fmin=0fmax=sr/2 隐式创建了梅尔过滤器(请参阅 docs here)。要正确绘制频谱图,librosa.display.specshow 需要知道它是如何创建的,即使用了何种采样率 sr(使时间轴正确)以及使用什么频率范围使频率轴正确.虽然 librosa.feature.melspectrogram 默认为 0 - sr/2,但遗憾的是 librosa.display.specshow 默认为 0 - 11050(请参阅 here)。这描述了 librosa 0.8——我可以想象未来会发生这种变化。

要使其正常工作,请显式添加 fmax 参数。要同时获得正确的时间轴,请将 sr 参数添加到 librosa.display.specshow

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

sr = 44100
t = np.linspace(0,1,sr)
y = 0.1 * np.sin(2 * np.pi * 4096 * t)

M = librosa.feature.melspectrogram(y=y,sr=sr,fmax=sr/2)
M_db = librosa.power_to_db(M,ref=np.max)
librosa.display.specshow(M_db,y_axis='mel',x_axis='time',fmax=sr/2)
plt.show()

correct mel spectrogram plot