使用Python API从SoundCloud流式传输歌曲
我正在写一个小程序,目的是从SoundCloud上播放一首歌。我的代码是:
import soundcloud
cid="==="
cs="==="
un="==="
pw="==="
client = soundcloud.Client(
client_id=cid,
client_secret=cs,
username=un,
password=pw
)
print "Your username is " + client.get('/me').username
# fetch track to stream
track = client.get('/tracks/293')
# get the tracks streaming URL
stream_url = client.get(track.stream_url, allow_redirects=False)
# print the tracks stream URL
print stream_url.location
它只是打印出用户名和曲目的网址。打印出来的内容大概是这样的:
Your username is '==='
https://ec-media.soundcloud.com/cWHNerOLlkUq.128.mp3?f8f78g6njdj.....
然后,我想从这个网址播放MP3。我可以用urllib来下载它,但如果文件很大,就会花很多时间。
有什么好的方法可以直接播放MP3吗?谢谢!!
1 个回答
3
在使用我这里提到的解决方案之前,你需要知道一点,就是你必须在你的应用程序中某个地方提到SoundCloud,并且可能还要在用户看到的音频播放器中显示它是通过SoundCloud提供的。如果不这样做,那就不太公平,可能还会违反他们的使用条款。
track.stream_url
并不是与mp3文件相关的最终网址。所有的音频内容都是在你发送一个http请求时才会“按需”提供的,也就是说,只有当你使用track.stream_url
发送请求时,才会被重定向到实际的mp3流(这个流是专门为你创建的,并且会在接下来的15分钟内过期)。
所以如果你想指向音频源,首先你需要获取流的重定向网址:
下面是C#代码,它实现了我所说的内容,给你一个主要的思路——只需将其转换为Python代码即可;
public void Run()
{
if (!string.IsNullOrEmpty(track.stream_url))
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(track.stream_url + ".json?client_id=YOUR_CLIENT_ID");
request.Method = "HEAD";
request.AllowReadStreamBuffering = true;
request.AllowAutoRedirect = true;
request.BeginGetResponse(new AsyncCallback(ReadWebRequestCallback), request);
}
}
private void ReadWebRequestCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(callbackResult);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
this.AudioStreamEndPointUrl = myResponse.ResponseUri.AbsoluteUri;
this.SearchCompleted(this);
}
myResponse.Close();
}