Reputation: 602
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
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
Reputation: 44828
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())
See this file for an example of base64 encoding of a file.
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