Librosa 音频处理:绘制波形图和频谱图及错误解决

本文将使用 Librosa 库绘制音频的波形图和频谱图,并解决在绘制频谱图时出现的 'AxesSubplot' object has no attribute 'get_array' 错误。

import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
matplotlib.use('Agg')

# 加载两个音频文件
y1, sr1 = librosa.load('p232_036.wav')
y2, sr2 = librosa.load('enhanced_p232_036.wav')

# 绘制波形图
plt.subplot(2, 2, 1)
librosa.display.waveplot(y1, sr=sr1)
plt.title('Audio 1')
plt.subplot(2, 2, 3)
librosa.display.waveplot(y2, sr=sr2)
plt.title('Audio 2')

# 计算并绘制频谱图
D1 = librosa.amplitude_to_db(librosa.stft(y1), ref=np.max)
D2 = librosa.amplitude_to_db(librosa.stft(y2), ref=np.max)
fig, axs = plt.subplots(2, 2)
img1 = librosa.display.specshow(D1, y_axis='linear', x_axis='time', sr=sr1, ax=axs[0, 1])
# 将 plt.colorbar() 改为 axs[0,1].figure.colorbar()
axs[0, 1].figure.colorbar(img1, ax=axs[0, 1], format='%+2.0f dB',shrink=0.7)
axs[0, 1].set_title('Audio 1')
axs[0, 1].set_yscale('log')
img2 = librosa.display.specshow(D2, y_axis='linear', x_axis='time', sr=sr2, ax=axs[1, 1])
# 将 plt.colorbar() 改为 axs[1,1].figure.colorbar()
axs[1, 1].figure.colorbar(img2, ax=axs[1, 1], format='%+2.0f dB',shrink=0.7)
axs[1, 1].set_title('Audio 2')
axs[1, 1].set_yscale('log')

plt.tight_layout()
plt.show()

错误解决

在绘制频谱图时,使用 plt.colorbar() 函数会导致 'AxesSubplot' object has no attribute 'get_array' 错误。这是因为 plt.colorbar() 函数试图从 AxesSubplot 对象中获取 get_array 属性,而该属性并不存在。

解决方法是将 plt.colorbar() 函数改为 axs[0,1].figure.colorbar()axs[1,1].figure.colorbar(),分别用于绘制 img1img2 的颜色条。

通过这种方式,我们可以成功绘制音频的波形图和频谱图,并解决出现的错误。

Librosa 音频处理:绘制波形图和频谱图及错误解决

原文地址: https://www.cveoy.top/t/topic/nqQg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录