【问题标题】:Stream a song from SoundCloud using the Python API使用 Python API 从 SoundCloud 流式传输歌曲
【发布时间】:2014-04-02 12:12:31
【问题描述】:

我正在编写一个小程序,它应该从 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 的最佳方式是什么? 谢谢!!

【问题讨论】:

    标签: python python-2.7 mp3 soundcloud playback


    【解决方案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();
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      相关资源
      最近更新 更多