user2238884
user2238884

Reputation: 602

Convert WAV to base64

I have some wave files (.wav) and I need to convert them in base64 encoded strings. Could you guide me how to do that in Python/C/C++ ?

Upvotes: 4

Views: 11867

Answers (2)

user2238884
user2238884

Reputation: 602

@ForceBru's answer

import base64 
enc=base64.b64encode(open("file.wav").read())

has one problem. I noticed for some WAV files that I encoded the string generated was shorter than expected.

Python docs for "open()" say

If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability.

Hence, the code snippet doesn't read in binary. So, the below code should be used for better output.

import base64
enc = base64.b64encode(open("file.wav", "rb").read())

Upvotes: 10

ForceBru
ForceBru

Reputation: 44828

Python

The easiest way

from base64 import b64encode

f=open("file.wav")
enc=b64encode(f.read())
f.close()

Now enc contains the encoded value.

You can use a bit simplified version:

import base64

enc=base64.b64encode(open("file.wav").read())

C

See this file for an example of base64 encoding of a file.


C++

Here you can see the base64 conversion of strings. I think it wouldn't be too difficult to do the same for files.

Upvotes: 7

Related Questions