Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode base64 String directly to binary audio format

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?

like image 618
ddd Avatar asked Feb 26 '26 15:02

ddd


1 Answers

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.

like image 85
BertMacklinFBI Avatar answered Feb 28 '26 06:02

BertMacklinFBI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!