How to play mp3 from URL

Question:

I’m trying to write a python script that will play mp3 from Soundcloud URL

This is what I’ve already done:

from urllib.request import urlopen

url = "soundcloud.com/artist/song.mp3"
u = urlopen(url)

data = u.read(1024)

while data:
   player.play(data)
   data = u.read(1024)

I tried pyaudio with many options like changing formats, channels, rate.
and I just get strange sound from the speakers, I searched Google for pyaudio playing mp3 and didn’t found any information.

I tried pygame by creating Sound object by passing the bytes from the mp3 and then just by executing the play function. I am not getting any errors: the script runs but nothing is playing.

I’m working with Python 3 and Ubuntu.

Asked By: LichKing

||

Answers:

Check if you can download file manually using that URL. If its protected site with username/passwd, you may need to take care of that first.

If not, here is a working code that downloads file from url using urllib2 and then plays it using pydub.

Its a two step process where first mp3 file is downloaded and saved to file and then played using external player.

import urllib2
from pydub import AudioSegment
from pydub.playback import play


mp3file = urllib2.urlopen("http://www.bensound.org/bensound-music/bensound-dubstep.mp3")
with open('./test.mp3','wb') as output:
  output.write(mp3file.read())

song = AudioSegment.from_mp3("./test.mp3")
play(song)

** Update **
You did mention that you need streaming from web. In that case you may want to look at GStreamer with Python Bindings

Here is a SO link for that.

Answered By: Anil_M

Sorry but I do not have Python3 to test here, to stream mp3 using pyaudio you will need decode it in PCM data, I know that pymedia can do it, but it is too old and just support python27.

To do this the right way you will need to know some attributes of your audio, things like samplerate, number of channels, bit resolution, to set it in the pyaudio.

I can show how I do it using python27 + pyaudio, first I will show how it is done to stream .wav

from urllib2 import urlopen
#to python3.x
#from urllib.request import urlopen
import pyaudio


pyaud = pyaudio.PyAudio()

srate=44100

stream = pyaud.open(format = pyaud.get_format_from_width(1),
                channels = 1,
                rate = srate,
                output = True)


url = "http://download.wavetlan.com/SVV/Media/HTTP/WAV/NeroSoundTrax/NeroSoundTrax_test4_PCM_Mono_VBR_8SS_44100Hz.wav"
u = urlopen(url)

data = u.read(8192)

while data:

    stream.write(data)
    data = u.read(8192)

choose large buffer, python is slow in while loop, i did it using chunks of size 8192, note that format, channels and rate are the rigth attributes for this wav file, so for .wav we not need decode, it is a PCM data, now for mp3 we will need decode and put in PCM format to stream.

Lets try using pymedia

from urllib2 import urlopen
import pyaudio
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
dm= muxer.Demuxer( 'mp3' )


pyaud = pyaudio.PyAudio()

srate=44100

stream = pyaud.open(format = pyaud.get_format_from_width(2),
                channels = 1,
                rate = srate,
                output = True)


url = "http://www.bensound.org/bensound-music/bensound-dubstep.mp3"

u = urlopen(url)

data = u.read(8192)

while data:

    #Start Decode using pymedia
    dec= None
    s= " "
    sinal=[]
    while len( s ):
        s= data
        if len( s ):
            frames= dm.parse( s )
            for fr in frames:
                if dec== None:
                    # Open decoder
                    dec= acodec.Decoder( dm.streams[ 0 ] )
                r= dec.decode( fr[ 1 ] )
                if r and r.data:
                    din = r.data;
            s=""
    #decode ended

    stream.write(din)
    data = u.read(8192)

This may be secret, because I never saw anyone showing how this can be done in python, for python3 I not know anything that can decode .mp3 into pieces like pymedia do.

Here these two codes are streming and working for .wav and .mp3

Answered By: ederwander

If you happen to have VLC installed (or are willing to install it), then this should work:

import vlc
p = vlc.MediaPlayer("http://your_mp3_url")
p.play()

This has the advantage that it works with everything VLC works with, not just MP3. It can also be paused if you want to.

You can install vlc for python using

pip install python-vlc
Answered By: randomdude999

you can use python-vlc

pip install python-vlc
import vlc as v
mp3 = v.MediaPlayer("file_path_of_mp3")
mp3.play()
Answered By: Jai Sai
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.