How to decode base64 String directly to binary audio format

旧时模样 提交于 2021-02-07 05:51:07

问题


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.

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)

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)

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

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

What is the correct way to do this?


回答1:


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

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)

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.



来源:https://stackoverflow.com/questions/50279380/how-to-decode-base64-string-directly-to-binary-audio-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!