从Angular Controller控制SoundCloud js sdk

时间:2014-08-23 13:27:37

标签: javascript html angularjs soundcloud

我正在尝试从角度控制器中控制SoundCloud js sdk,但我不知道该怎么做。文档坚持要从脚本标记加载:

<script src="//connect.soundcloud.com/sdk.js"></script>

但是在部分视图中使用会导致脚本无法加载。我已经尝试了一些可以加载脚本并将其从控制器添加到DOM中的内容,如下所示:

        function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

var Initialize = function() {

    SC.initialize({
        client_id: 'YOUR_CLIENT_ID'
    });

    SC.get('/tracks', { q: $scope.searchQuery, license: 'cc-by-sa' }, function(tracks) {
        $scope.searchResults = tracks;
        console.log(tracks);
    });
};

loadScript("http://connect.soundcloud.com/sdk.js", Initialize); 

但是我无法从控制器中的其他方法访问播放器。

我已经研究过使用http api,但它看起来很混乱,最好使用sdk。

我对Angular很新,对SoundCloud sdk来说是全新的。将Soundcloud作为服务引入是否最好?模块?我该怎么做?

我的控制器

angular.module('RoomCtrl', []).controller('RoomController', function($scope ,$http) {

$scope.tagline = 'the square root of 69 is 8 somethin';

$scope.play = function(id) {
    SC.stream("/tracks/" + id, function(sound){
        sound.play();
    });
}

$scope.searchQuery = "Trophies";

});

我的部分

<style>
html                    { overflow-y:scroll; }
body                    { padding-top:50px; }
#todo-list              { margin-bottom:30px; }
</style>
<div class="jumbotron text-center">
<h1>SoundCloud Player</h1>

<p>{{ tagline }}</p>

<div ng-click="play()">Play TUNES</div>
<div ng-click="pause()">PUASE</div>
</div>
<input type="text" ng-model="searchQuery"/>

<ul>
<li ng-repeat="songs in searchResults" ng-click="play(songs.id)">
    {{songs.title}}
</li>
</ul>

总体问题:

如何在控制器的任何位置使用SC?

如何在不使用脚本标记的情况下加载sdk?

1 个答案:

答案 0 :(得分:3)

我建议您使用Soundcloud作为服务,这样您就可以从任何地方访问播放器。

当您调用SC.stream时,您必须将该对象声音保存在某个地方,因为该对象具有停止,暂停,恢复,onfinish等事件的方法。

This code is working:
$scope.play = function(id){
   SC.stream("/tracks/" + id ,function(sound){
      // Save sound, it holds all the data needed to stop, resume, etc.
      $scope.soundObj = sound;
      sound.play({
      onfinish: function() {              
          //Start a new song or something.
        }
      });
  });
}

$scope.pause = function(){
  $scope.soundObj.pause();
}

我知道这个答案已经晚了,但可以帮助那些寻找同样事情的人。