wave包的使用

722 阅读1分钟

转换wav格式音频为pcm格式

            import wave
            platform_sample_rate = tts_info.get("sample_rate")
            wave_out = wave.open("audition.wav", 'wb')
            wave_out.setnchannels(1)
            wave_out.setsampwidth(2)
            wave_out.setframerate(platform_sample_rate)
            wave_out.writeframes(voice)
            wave_out.close()
            with open("audition.wav", 'rb') as f:
                voice = f.read()
            return voice

从本地音频文件读取出音频信息

    with wave.open(path, "rb") as f:
        # 读取格式信息
        # 一次性返回所有的WAV文件的格式信息,它返回的是一个组元(tuple):声道数, 量化位数(byte单位), 采
        # 样频率, 采样点数, 压缩类型, 压缩类型的描述。wave模块只支持非压缩的数据,因此可以忽略最后两个信息
        params = f.getparams()
        nchannels, sampwidth, framerate, nframes = params[:4]

        # 读取声音数据,传递一个参数指定需要读取的长度(以取样点为单位)
        str_data = f.readframes(nframes)
        codec_format = {"sample_rate": framerate, "bit_depth": sampwidth * 8, "num_of_channel": nchannels}

        return str_data, codec_format