You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行音频梅尔频谱生成代码时遭遇TypeError: 'pad_width' must be of integral type错误的修复方法咨询

修复librosa梅尔频谱生成中的TypeError: pad_width must be of integral type错误

我刚碰到过一模一样的问题,这个错误本质上是因为你的音频输入不符合librosa的要求,主要是两个小问题:

错误原因分析

  1. 音频数据类型不对:wavfile.read()返回的音频振幅amp是整数类型(通常是int16),而librosa的STFT(短时傅里叶变换)要求输入是浮点型数组,且数值范围最好在[-1, 1]之间。
  2. 多声道音频未处理:如果你的音频是立体声(双声道),amp会是一个二维数组(形状为(样本数, 2)),但librosa的melspectrogram只接受一维的单声道数据,这会导致后续窗口计算时出现非整数的pad宽度,触发报错。

修复方案

我们只需要修改readAudio函数,把这两个问题解决掉:

修改后的完整代码

from scipy import signal 
import matplotlib.pyplot as plt 
import librosa 
import librosa.display 
import numpy as np 
from playsound import playsound 
from scipy.io import wavfile 

overlap = 1024 
frame_length = 2048 

def readAudio(audio): 
    fs, amp = wavfile.read(audio) 
    dt = 1 / fs 
    n = len(amp) 
    t = dt * n 

    # 处理多声道:如果是立体声,转换成单声道(取两个声道的均值)
    if len(amp.shape) > 1:
        amp = np.mean(amp, axis=1)
    
    # 转换为浮点型并归一化到[-1, 1]范围
    if amp.dtype == np.int16:
        amp = amp / 32768.0
    elif amp.dtype == np.int32:
        amp = amp / 2147483648.0

    # 截取中间1秒的音频(原逻辑保留)
    if t > 1.0: 
        amp = amp[int((t / 2 - 0.5) / dt):int((t / 2 + 0.5) / dt)] 
        n = len(amp) 
        t = dt * n 
    return (amp, fs, n, t) 

# 读取音频
amp, fs, n ,t = readAudio(r'C:\Users\mehta\Desktop\SVDwav\2510-phrase.wav') 
# playsound(r'C:\Users\mehta\Desktop\SVDwav\2510-phrase.wav') 

# 生成梅尔频谱
S = librosa.feature.melspectrogram(y=amp, sr=fs, n_fft=frame_length, hop_length=overlap, power=1) 

# 可视化
fig = plt.figure(figsize=(10,4)) 
librosa.display.specshow(librosa.power_to_db(S, ref=np.max), y_axis='mel', fmax=8000, x_axis='time') 
plt.colorbar(format='%+2.0f dB') 
plt.title('Mel spectrogram') 
plt.tight_layout()
plt.show()  # 加上这行才能显示图像哦

关键修改点说明

  • 多声道处理:通过判断amp.shape的维度,如果大于1就对声道轴取均值,转换成单声道。
  • 数据类型转换:根据音频的整数类型(int16或int32),将数值归一化到[-1, 1]的浮点型,完全符合librosa的输入要求。
  • 去掉了原代码中多余的amp*1,现在直接传入处理好的浮点型amp即可。

这样修改后,应该就能顺利生成梅尔频谱图了。

内容的提问来源于stack exchange,提问作者Mehtab Ur Rahman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:47:28