2010-09-25 127 views
1

我正在使用jQuery音頻播放器'jPlayer',我有一個循環創建了一些jPlayer獨特實例,然後將點擊'jPlayer play'分配給另一部分每個實例的文檔..問題是jPlayer使用內部ready: function() {}來分配音頻路徑並加載文件..我需要等待這個函數完成後再繼續循環。等待jPlayer在繼續循環之前完成加載文件

僞代碼是這樣的:

for loop{ 

create jPlayer div; 

instantiate jPlayer and assign audio file in the ready(); // need to wait before continuing 

assign an on click event to play file; 
} 

我相信這是關於使用隊列,但我不知道如何實現它?非常感激任何的幫助!

回答

2

您可以嘗試這樣的事:

function initPlayer(playerQueue){ 
    if(playerQueue.length > 0) { 
    var player = playerQueue.pop(); // get our options hash for this iteration 
    var container = $('<div id="'+player.container+'"></div>').appendTo('body'); 

    $(container).jPlayer({ 
     ready: function(){ 
     var _e = this.element; 
     _e.jPlayer('setFile', player.file); 
     var timer = setInterval(function(){ 
      if(_e.jPlayer('getData', 'diag.loadPercent') == 100){ 
       $(player.control).click(function(){ 
        // assign your handler 
       }); 
       clearInterval(timer); // clear the interval 
       initPlayer(playerQueue); // invoke the next player init 
      } 
     },500); 
     }, 
     /* ... other options ... */ 
    }); 
    } 
} 

initPlayer([ 
    {container: 'audio-1', file: 'uri/for/file', control: '#button-1'}, 
    {container: 'audio-2', file: 'uri/for/file', control: '#button-2'}, 
    {container: 'audio-3', file: 'uri/for/file', control: '#button-3'}, 
    {container: 'audio-4', file: 'uri/for/file', control: '#button-4'} 
]); 

我們基本上擺脫了明確的循環,而是使用現成功能本身通過initPlayer功能,推進構建迭代。通過使用一個數組,我們可以使用pop(),它將得到數組的最後一個元素,同時將它從數組中移除。我們等待調用initPlayer,直到通過每500毫秒輪詢播放器的負載百分比來獲得100的負載百分比。

這只是一個建議,可能需要很多工作......我從來沒有使用過jPlayer,而且我正在從文檔中盲目飛行,所以不要期望它能夠開箱即用:-)。

+1

你是絕對的天才!非常感謝,我真的很感激它,我不得不亂它一下,添加jPlayer('load');在我們指定文件路徑以實際加載它之後..並且jPlayer喜歡返回99.9999999而不是100,這很奇怪。我得到一個「Uncaught TypeError:不能每次讀取未定義的屬性'容器'(代碼片段中的第4行)。儘管希望儘可能達到底線......再次感謝! (: – greenimpala 2010-09-25 20:34:55

+1

hmm throw in'console.log(player); console.log(playerQueue);'在創建了'div'的行之前,在Firefox/Firebug中進行調試,並查看每個內容的錯誤。可能會解決這個問題,但是可以通過明確地將你的對象數組附加到'window'對象並將其明確地稱爲:-) – prodigitalson 2010-09-25 21:00:05

+0

Ahh剛剛做了你說什麼,出於某種原因我刪除了if(playerQueue.length> 0)..所以它試圖處理空數組。感謝那 :) !! – greenimpala 2010-09-25 21:44:21