Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an audiostream in python

Amazingly, in bash, you can do

$ curl http://mp3.streampower.be/radio1-high.mp3 > test.mp3

with an audiostream and then ^C out, and you will have a working mp3 file, leading me to believe I could have this automated in python, but I can't find how.

If i just do

file('python.mp3', 'w').write(urllib2.urlopen("http://mp3.streampower.be/radio1-high.mp3").read())

it doesn't even read the stream.

Is there something like BufferedInputReader from java in python or can anyone give me some pointers as to how I would go about doing this? Reading an audiostream and getting it to stop reading after a while.

Thanks

like image 468
thepandaatemyface Avatar asked Jul 14 '10 10:07

thepandaatemyface


1 Answers

You'd probably do better to save the file-like object from urllib2.urlopen() and then use its read method in a loop with a size parameter:

#!/usr/bin/python

import urllib2

f=file('python.mp3', 'w')

url=urllib2.urlopen("http://mp3.streampower.be/radio1-high.mp3")

while True:
    f.write(url.read(1024))

Your code was calling read without a size parameter -- which tries to read the whole thing. It's a stream, so that will be a while. If the stream ever closes, then your call to write could proceed, and you'd go from no file to a huge file in no time.

My sample code here will build you an mp3 file nice and slow. You may need to tweak the 1024 if the streams are sending much faster than typical mp3 bitrates, but this should be fine. (A 128kbps stream would involve 16 system calls per second to write(2), which shouldn't be any stress at all. But at 10mbit speeds or higher, it'd hurt, and you should use a larger read size.)

like image 195
sarnold Avatar answered Sep 24 '22 14:09

sarnold