使用Soundcloud API流式播放特定歌曲

时间:2016-01-07 17:34:37

标签: javascript soundcloud

我还在学习如何使用API​​ - 这给我带来了麻烦。我相信我的代码是正确的,但是当我尝试使用简单的JavaScript onclick函数流式播放歌曲时没有任何反应。

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();
    });
}

2 个答案:

答案 0 :(得分:2)

首先,使用resolve端点获取该轨道的API网址:

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]"}

调用GET请求该网址,我们可以获得该广告的id,即43377447

将您的JS更改为指向tracks端点:

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

Working JSFiddle with your client_id.

答案 1 :(得分:0)

如果有人想知道为什么在Chrome中流无效,根据此issue,您应该反转实时消息传递协议,强制Chrome使用html5代替闪存。

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

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