python读取wav并显示波形

目标:使用python读取wav文件并显示波形

代码

def wavReader(wavFile):
    # 读取wav文件
    wav = wave.open(wavFile, 'rb')
    # 根据采样频率将data中的二进制数据转换为数组
    if wav.getsampwidth() == 2:
        data = np.frombuffer(wav.readframes(wav.getnframes()), dtype=np.int16)
    elif wav.getsampwidth() == 4:
        data = np.frombuffer(wav.readframes(wav.getnframes()), dtype=np.int32)
    # 根据声道绘制波形图
    if wav.getnchannels() == 1:
        time = np.arange(0, wav.getnframes()) * (1.0 / wav.getframerate())
        plt.plot(time, data)
    elif wav.getnchannels() == 2:
        data.shape = -1, 2
        data = data.T
        time = np.arange(0, wav.getnframes()) * (1.0 / wav.getframerate())
        plt.subplot(2, 1, 1)
        plt.plot(time, data[0])
        plt.subplot(2, 1, 2)
        plt.plot(time, data[1], c="g")
    plt.show()

你可能感兴趣的:(python,开发语言)