11

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.

runeh
  • 3,771
  • 1
  • 21
  • 16
  • Can you specify more informations? What kind of streaming is it? Plain mp3 (could you also Save it with 'Save as ...')? If not, the protocol has probalby more informations in it, than just the audio information. – Andre Bossard Oct 09 '08 at 14:39
  • this ultimately worked, but it never exited the while clause. Do I need to add additional code so it finishes properly? – ChrisArmstrong Jul 13 '13 at 20:59

3 Answers3

15

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
  • 390,455
  • 97
  • 512
  • 589
4

The best way for this is:

urllib.urlretrieve(stream_url, target_path);
animuson
  • 53,861
  • 28
  • 137
  • 147
Boiler
  • 41
  • 1
1

Perhaps the syntax changed from the previous urllib answer (that got me to the correct answer btw), but this syntax works for python3:

import urllib.request

urllib.request.urlretrieve(stream_url, target_path)