如何将base64字符串直接解码为二进制音频格式 [英] How to decode base64 String directly to binary audio format

查看:261
本文介绍了如何将base64字符串直接解码为二进制音频格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

音频文件通过API发送给我们,该API是Base64编码的PCM格式.我需要将其转换为PCM,然后转换为WAV进行处理.

Audio file is sent to us via API which is Base64 encoded PCM format. I need to convert it to PCM and then WAV for processing.

我能够解码->保存到pcm->从pcm读取->使用以下代码另存为wav.

I was able to decode -> save to pcm -> read from pcm -> save as wav using the following code.

decoded_data = base64.b64decode(data, ' /')
with open(pcmfile, 'wb') as pcm:
    pcm.write(decoded_data)
with open(pcmfile, 'rb') as pcm:
    pcmdata = pcm.read()
with wave.open(wavfile, 'wb') as wav:
    wav.setparams((1, 2, 16000, 0, 'NONE', 'NONE'))
    wav.writeframes(pcmdata)

如果我可以将输入字符串解码为二进制并将其另存为wav,会容易得多.所以我在在python中将字符串转换为二进制的过程中做了类似的事情

It'd be a lot easier if I could just decode the input string to binary and save as wav. So I did something like this in Convert string to binary in python

  decoded_data = base64.b64decode(data, ' /')
    ba = ' '.join(format(x, 'b') for x in bytearray(decoded_data))
    with wave.open(wavfile, 'wb') as wav:
        wav.setparams((1, 2, 16000, 0, 'NONE', 'NONE'))
        wav.writeframes(ba)

但是我得到了错误需要一个类似字节的对象,而不是 wav.writeframes 上的'str'.

But I got error a bytes-like object is required, not 'str' at wav.writeframes.

还尝试了 base54.decodebytes()并得到了相同的错误.

Also tried base54.decodebytes() and got the same error.

正确的方法是什么?

推荐答案

在我的一个项目中,我也遇到了类似的问题.

I also faced a similar problem in a project of mine.

我能够将base64字符串直接转换为wav:

I was able to convert base64 string directly to wav :

import base64
encode_string = base64.b64encode(open("audio.wav", "rb").read())
wav_file = open("temp.wav", "wb")
decode_string = base64.b64decode(encode_string)
wav_file.write(decode_string)

首先将其编码为base64.然后以wav格式创建文件,并将解码的base64字符串写入该文件.

First encode it into base64. Then create a file in wav format and write the decoded base64 string into that file.

我知道这是一个很晚的答案.希望这会有所帮助.

I know this is a very late answer. Hope this helps.

这篇关于如何将base64字符串直接解码为二进制音频格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆