I am trying to debug a larger audio project with this example. I load an mp3 file, base64 encode it, decode, then save it to disk. Only the resulting file isn't all there, even though the base64 version look the same:

import base64
with open('/Users/Public/Music/119-the_killers-spaceman.mp3') as f:
mp3 = f.read()
>>> len(mp3)
1435
>>> b64 = base64.b64encode(mp3)
>>> len(b64)
1916 #I expect it to become 25% larger when encoded.
>>> MP3 = base64.b64decode(b64)
>>> f.close()
>>> F = open('test.mp3','wb')
>>> F.write(MP3)
>>> F.close()
>>> len(MP3)
1435

data is the same:

>>> MP3[:100]
'ID3\x03\x00\x00\x00\x00\x05GTRCK\x00\x00\x00\x06\x00\x00\x0019/24TIT2\x00\x00\x00\t\x00\x00\x00SpacemanTPE1\x00\x00\x00\x0c\x00\x00\x00The KillersTALB\x00\x00\x00\x1b\x00\x00\x00Funky New Year 2009: I'
>>> mp3[:100]
'ID3\x03\x00\x00\x00\x00\x05GTRCK\x00\x00\x00\x06\x00\x00\x0019/24TIT2\x00\x00\x00\t\x00\x00\x00SpacemanTPE1\x00\x00\x00\x0c\x00\x00\x00The KillersTALB\x00\x00\x00\x1b\x00\x00\x00Funky New Year 2009: I'

actual file: 2k, not 2.5MB.

What am I doing wrong? And hopefully this explains why I am having problems saving WAV files sent to my server that are base64 encoded too.

有帮助吗?

解决方案

I'm guessing this is on Windows. Windows has an interesting property when you open a file in text mode, it stops at the first Ctrl-Z (\x1a) character that it encounters. Any compressed file will look like a random sequence of bytes, meaning that value is bound to occur early in the file.

Open the file in binary mode:

with open('/Users/Public/Music/119-the_killers-spaceman.mp3', 'rb') as f:
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top