Play audio from URL

Please tell me and, if possible, provide a working code with comments that could play audio from the buffer?

The question is that I found a working code that writes an audio stream to an mp3 file:

import requests

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

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

I thought that since it is being written to a file, then it can be played from some kind of buffer, am I right in thinking? The following ridiculous attempts were made (obviously not working):

import requests
import simpleaudio as sa

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

with r:
        for block in r.iter_content(1024):
            play_obj = sa.play_buffer(block, 1, 2, 44100)
    except KeyboardInterrupt:

Please tell me how to write not to a file with that first code, but to redirect to a simpleaudio stream … I understand that I am doing something wrong with the buffer, maybe some transformations need to be done or I’m not letting it in a loop. Please do not scold too much …

Hi Stas,

This will be a small audience here, and even smaller at this time of the

year when many people will be away. I expect that, like me, most of them

will have never even heard of simpleaudio before now.

Instead of telling us that your attempts were “ridiculous” (what was

ridiculous about them?), it would be more helpful to tell us what

happened. Did you get an error? Does simpleaudio claim to support

streaming mp3? What do the docs for simpleaudio.play_buffer tell you?

If simpleaudio doesn’t support mp3, then there is nothing you can do to

get it to play a streaming mp3. You could look for another library that

supports playing mp3, or you can use another library to convert the

streaming mp3 to some format that simpleaudio plays.

Googling suggests that there are numerous Python libraries that support

playing streaming mp3s:

possibly the best may be the Python bindings to VLC

which plays a wide variety of media formats, both from files and


# Not tested

import vlc

p = vlc.MediaPlayer(stream_url)

Thanks for the tip. I’ve tried vlc. I am working in windows. This code works out and just ends. Shows no errors.

Sorry Stas,

I don’t understand what you mean by “this code works out”. Does it work?
Does it play sound? How do you know the stream is valid?

Can you play the stream in VLC itself?