2012-03-10 31 views
3

我創建了自己的HTML5音頻播放器,能夠處理播放列表。我創建了一個自定義myPlaylist對象,其中包括所有的play(),pause(),stop()和其他所需的功能。這一切都正常工作,但此外,我需要知道音頻文件何時結束以便自動開始播放下一個音頻文件。使用HTML5音頻和jQuery調用對象(this)的引用

下面的代碼的相關部分我使用:

function myPlaylist(){ 

    var player = document.createElement('audio'); 
    var audio = $(player).get(0); 

    this.next = function next(){ 
     // Picks next song in the playlist and plays it 
     ... 
    }; 

    $(audio).bind('ended', function() { 
     alert("Song is finished!"); 
     // Here I want to call to my next() function 
    }); 
} 

我一直無法弄清楚如何做到這一點。我已經嘗試過幾種組合,例如$(this).next(),這似乎是最合理的,實際上顯示警報,但隨後不執行任何操作,也是this.next(),它也顯示警報,但隨後顯示錯誤,因爲this引用HTML5音頻元素,它沒有next()功能。

我也嘗試另一種方法,使用

audio.onended = function(){ 
    alert("Song is finished!"); 
    $(this).next(); 
}; 

但那些甚至不觸發警報。另外audio.ended不起作用。

所以,我現在基本無能爲力,有沒有人有任何想法我做錯了什麼?提前致謝。

哦,我測試過這一切,谷歌Chrome和Safari的最新版本的Mac OS X.


編輯HTML5 audio playlist - how to play a second audio file after the first has ended?給出的建議,我也嘗試過下面的代碼

player.addEventListener("ended", function() { 
    alert("Song is finished!"); 
    $(this).next(); 
}); 

而且

player.addEventListener("ended", next); 

他們都不工作,雖然第一個正確顯示警報。


EDIT 2使用我碰到this question來搜索,這也可能是與我的問題,所以爲了擺脫與參考任何可能的麻煩來this,我添加了一個新的變量引用對象本身,所以我現在基本上是與工作:

function myPlaylist(){ 

    var player = document.createElement('audio'); 
    var audio = $(player).get(0); 
    var me = $(this); 

    this.next = function next(){ 
     // Picks next song in the playlist and plays it 
     ... 
    }; 

    $(audio).bind('ended', function() { 
     alert("Song is finished!"); 
     me.next(); 
    }); 
} 

但後來我得到一個錯誤,說對象沒有一個方法next()

我不知道還有什麼可以嘗試...任何額外的信息將不勝感激,謝謝!

+0

事件名稱通常不開頭的(如在audio.onended),這看起來更像是IE瀏覽器給我。你有沒有嘗試audio.ended你的第二個例子? – marue 2012-03-10 21:11:54

+0

是的,我已經嘗試過,同樣的結果,警報沒有顯示。但我不知道事件名稱取決於瀏覽器。謝謝你的提示。 – 2012-03-10 22:24:42

回答

2

有一個處理ended事件here的HTML5播放列表示例,如果有幫助?

在事件處理您引用this,但在這種情況下this指的是抓住了事件的DOM元素,即你audio元素..試試這個來代替:在Chrome和Safari

function myPlaylist(){ 

    var self = this; 
    var player = document.createElement('audio'); 

    this.next = function(){ 
     // Picks next song in the playlist and plays it 
     ... 
    }; 

    player.addEventListener("ended", function() { 
     alert("Song is finished!"); 
     self.next(); 
    }); 

} 

see the MDN for more info on the this keyword

+0

謝謝,我沒有看到那一個。我試過使用那裏提到的選項,但似乎也沒有工作。我將用新信息編輯問題。 – 2012-03-10 22:38:20

+0

更新的答案 - 可能的語法問題 – Lloyd 2012-03-11 00:37:34

+0

我認爲這兩個都是正確的,但無論如何,它也不工作:S – 2012-03-11 14:23:56