Record streaming and saving internet radio in python

madmaze picture madmaze · Nov 22, 2010 · Viewed 13.6k times · Source

I am looking for a python snippet to read an internet radio stream(.asx, .pls etc) and save it to a file.

The final project is cron'ed script that will record an hour or two of internet radio and then transfer it to my phone for playback during my commute. (3g is kind of spotty along my commute)

any snippits or pointers are welcome.

Answer

Jazzer picture Jazzer · Dec 8, 2015

The following has worked for me using the requests library to handle the http request.

import requests

stream_url = 'http://your-stream-source.com/stream'

r = requests.get(stream_url, stream=True)

with open('stream.mp3', 'wb') as f:
    try:
        for block in r.iter_content(1024):
            f.write(block)
    except KeyboardInterrupt:
        pass

That will save a stream to the stream.mp3 file until you interrupt it with ctrl+C.