2013-10-23 100 views
0

我正在構建一個網絡體驗的音頻播放器,它有一個音軌列表。這裏是控制音頻播放器的代碼。隨機從jquery html5音頻播放列表刷新頁面

$(document).ready(function() { 
jQuery(function($) { 
      var supportsAudio = !!document.createElement('audio').canPlayType; 
      if(supportsAudio) { 
       var index = 0, 
       playing = false; 
       mediaPath = 'audio/', 
       extension = '', 
       tracks = [ 
        {"track":1,"name":"track1","length":"00:55","file":"track1"}, 
        {"track":2,"name":"track2","length":"00:55","file":"track2"}, 
        {"track":3,"name":"track3","length":"00:55","file":"track3"}, 
        {"track":4,"name":"track4","length":"00:55","file":"track4"}, 
        {"track":5,"name":"track5","length":"00:55","file":"track5"} 
       ], 
       trackCount = tracks.length, 
       npAction = $('#npAction'), 
       npTitle = $('#npTitle'), 
       audio = $('#audio1').bind('play', function() { 
        playing = true; 
        npAction.text('Now Playing:'); 
       }).bind('pause', function() { 
        playing = false; 
        npAction.text('Paused:'); 
       }).bind('ended', function() { 
        npAction.text('Paused:'); 
        if((index + 1) < trackCount) { 
         index++; 
         loadTrack(index); 
         audio.play(); 
        } else { 
         audio.pause(); 
         index = 0; 
         loadTrack(index); 
        } 
       }).get(0), 
       li = $('#plUL li').click(function() { 
        var id = parseInt($(this).index()); 
        if(id !== index) { 
         playTrack(id); 
        } 
       }), 
       loadTrack = function(id) { 
        $('.plSel').removeClass('plSel'); 
        $('#plUL li:eq(' + id + ')').addClass('plSel'); 
        npTitle.text(tracks[id].name); 
        index = id; 
        audio.src = mediaPath + tracks[id].file + extension; 
       }, 
       playTrack = function(id) { 
        loadTrack(id); 
        audio.play(); 
       }; 

       extension = audio.canPlayType('audio/mpeg') ? '.mp3' : audio.canPlayType('audio/ogg') ? '.ogg' : ''; 
       loadTrack(index); 
      } 


}); 
}); 

有沒有一種方法來重新排列名爲軌道的變量裏面的列表?生成1到5的列表隨機拉?例如,名爲track2 track3 track4等的項目。可能會先玩嗎?我正在尋找一個頁面刷新隨機。

感謝您的幫助!

回答

0

您可以將一個playOrder字段添加到tracks變量,並讓一個函數遍歷每個on load併爲其分配一個隨機未使用的playOrder編號。

+0

哦,對,有道理!所以「track」字段就是「play order」,創建一個函數來隨機分配一個未使用的數字不應該太困難,我會試着弄明白這一點! Thanks dood! –