Skip to main content
 首页 » 编程设计

python之使用 Python API 从 SoundCloud 流式传输歌曲

2024年11月01日10zlslch

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