2016-01-09 396 views
1

如何不間斷地連續播放所有喜愛的歌曲?Soundcloud SDK 3.不間斷的喜歡(喜歡)歌曲流

我寫了一個js代碼,獲取我最喜歡的歌曲,隨機播放一個流。當第一首歌曲結束時,播放下一首隨機播放的歌曲。但我的目標是一個接一個地播放所有歌曲,直到我想手動停止它。

我的代碼:

var getRandom = function(min, max){ 
    return Math.round(Math.random() * (max - min) + min); 
} 

function playFon() { 
    SC.connect().then(function(){ 
    SC.get('/me').then(function(me) { 
     SC.get('/users/'+ me.id +'/favorites?limit=200').then(function(data) { 
       var num_of_res = data.length; 
       var sid = getRandom(0, num_of_res); 
       var song = '/tracks/' + data[sid].id; 

       SC.stream(song).then(function(player){ 

        player.on('play-start', function(){ 
         console.log('Playing '+ sid + ' ' + song); 
         console.log(data[sid]); 
        }).on('finish', function(){ 
         sid = getRandom(0, num_of_res); 
         song = '/tracks/' + data[sid].id; 

         console.log('Playing '+ sid + ' ' + song); 
         console.log(data[sid]); 

         SC.stream(song).then(function(player){ 
          player.play(); 
         }); 
        }); 

        player.play(); 

       }); 
     }); 
     }); 
    }).then(function(data){ 
     console.log('You are playing now.'); 
    }).catch(function(error){ 
     console.log('Error: ' + error.message); 
    }); 

} 

回答

2

我找到了解決辦法。我使用SoundManager2和遞歸函數nextTrack()來播放下一個隨機軌道。我認爲這也可以通過SoundCloud播放器完成。

var fav_songs_arr = []; 
var num_of_res = 0; 
var sid = 0; 
var url = ''; 

var getRandom = function(min, max){ 
    return Math.round(Math.random() * (max - min) + min); 
} 

var nextTrack = function(){ 
    soundManager.stopAll(); 
    sid = getRandom(0, num_of_res); 
    url = fav_songs_arr[sid].stream_url + '?consumer_key=' + app_id; 
    var mySound = soundManager.createSound({ 
     url: url, 
     onfinish: function(){ 
      nextTrack(); 
     } 
    }); 
    mySound.play(); 
} 

function playFon() { 
    SC.connect().then(function(){ 
     SC.get('/me').then(function(me) { 
     SC.get('/users/'+ me.id +'/favorites?limit=200').then(function(data) { 
       fav_songs_arr = data; 
       num_of_res = fav_songs_arr.length; 
       nextTrack(); 
      }); 
     }); 
    }).then(function(data){ 
     console.log('You are playing now.'); 
    }).catch(function(error){ 
     console.log('Error: ' + error.message); 
    }); 

}