我写了一个小程序,应该从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.....
然后,我想从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();
}