views:

981

answers:

3

What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python?

Thus far I've tried

target = open(target_path, "w")
conn = urllib.urlopen(stream_url)
while True:
    target.write(conn.read(buf_size))

This gives me data but its garbled or wont play in mp3 players.

+8  A: 

If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening target in binary mode:

target = open(target_path, "wb")
Adam Rosenfield
A: 

@Adam Rosenfield You're quite right. That was a stupid mistake, but now it works. Thanks

runeh
This answer should have been a comment to Adam's answer :)
xtofl
A: 

The best way for this is:

urllib.urlretrieve(stream_url, target_path);

Boiler