Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...