2014-04-02 56 views
1

我写一个小程序,应该从SoundCloud .. 我的码流的歌曲从SoundCloud一首歌:流使用Python API

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 

它只是打印usernsame,和轨道URL 它打印这样的东西:

Your username is '===' 
https://ec-media.soundcloud.com/cWHNerOLlkUq.128.mp3?f8f78g6njdj..... 

然后,我想从URL播放MP3。我可以使用urllib下载它,但如果它是一个大文件,它会花费很多时间。

什么是流的MP3的最佳方式是什么? 谢谢!

回答

1

使用该解决方案,我建议在此之前,你应该知道的事实,你必须在用户将看到它的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(); 

     }