[英]Stream a song from SoundCloud using the Python API
我正在编写一个应该从 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
它只是打印用户名和轨道 URL 它打印如下内容:
Your username is '==='
https://ec-media.soundcloud.com/cWHNerOLlkUq.128.mp3?f8f78g6njdj.....
然后,我想从 URL 播放 MP3。 我可以使用urllib下载它,但是如果它是一个大文件,则需要很多时间。
流式传输 MP3 的最佳方式是什么? 谢谢!!
在使用我在此建议的解决方案之前,您应该了解这样一个事实,即您必须将 SoundCloud 归功于应用程序中的某个位置,并且可能在您的音频播放器中,用户将看到它是通过 SoundCloud 提供的。 反其道而行之将是不公平的,并且可能违反他们的使用条款。
track.stream_url
不是与 mp3 文件关联的端点 URL。 当您使用track.stream_url
发送 http 请求时,所有相关的音频仅“按需”提供。 发送 http 请求后,您将被重定向到实际的 mp3 流(仅为您创建,并将在接下来的 15 分钟内到期)。
因此,如果您想指向音频源,您首先应该获取流的 redirect_url:
下面是执行我所说的 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.