使用Soundcloud API播放特定歌曲

Stream a specific song using Soundcloud API

本文关键字:播放 Soundcloud API 使用      更新时间:2023-09-26

我仍在学习如何使用API——这给我带来了麻烦。我相信我的代码是正确的,但当我尝试使用简单的JavaScriptonclick函数流式传输歌曲时,什么都不会发生。

HTML:

<head>
        <script src="https://connect.soundcloud.com/sdk/sdk-3.0.0.js"></script>
        <script src="good.js"></script>
</head>
    <body>
        <button onclick="playIt()">play adele</button>
    </body>

JavaScript:

SC.initialize({
        client_id: 'XXXXXXXXXX',
    });
function playIt(){
    var sound = SC.stream("/emberwaves/adele-set-fire-to-the-rain-remix", function(sound){
        sound.play();
    });
}

首先,使用resolve端点获取该音轨的API URL:

HTTP GET: https://api.soundcloud.com/resolve.json?url=https://soundcloud.com/emberwaves/adele-set-fire-to-the-rain-remix&client_id=[CLIENT_ID]

响应:

HTTP/1.1 302 Found
Access-Control-Allow-Headers: Accept, Authorization, Content-Type, Origin
Access-Control-Allow-Methods: GET, PUT, POST, DELETE
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Date
Cache-Control: no-cache
Content-Type: application/json; charset=utf-8
Date: Thu, 07 Jan 2016 19:54:36 GMT
Location: https://api.soundcloud.com/tracks/43377447.json?client_id=[CLIENT_ID]
Server: am/2
Status: 302 Found
Content-Length: 128
Connection: close
{"status":"302 - Found","location":"https://api.soundcloud.com/tracks/43377447.json?client_id=[CLIENT_ID]"}

调用该URL的GET请求,我们可以获得该轨道的id,即43377447

将JS更改为指向tracks端点:

var sound = SC.stream("tracks/43377447", function(sound){
    sound.play();
});

使用您的client_id使用JSFiddle。

对于任何想知道为什么Chrome中的流不起作用的人,根据这个问题,你应该反转实时消息传递协议,迫使Chrome使用html5而不是flash。

要解决此问题,您必须将JS更改为:

SC.stream("tracks/43377447").then(function(sound) {
    if (player.options.protocols[0] === 'rtmp') {
        player.options.protocols = player.options.protocols.reverse();
    }
    sound.play();
}