Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play mp3 from URL

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.

like image 383
LichKing Avatar asked Jul 03 '16 14:07

LichKing


2 Answers

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
like image 143
randomdude999 Avatar answered Oct 02 '22 04:10

randomdude999


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.

like image 24
Anil_M Avatar answered Oct 02 '22 02:10

Anil_M