我創建了自己的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()
。
我不知道還有什麼可以嘗試...任何額外的信息將不勝感激,謝謝!
事件名稱通常不開頭的(如在audio.onended),這看起來更像是IE瀏覽器給我。你有沒有嘗試audio.ended你的第二個例子? – marue 2012-03-10 21:11:54
是的,我已經嘗試過,同樣的結果,警報沒有顯示。但我不知道事件名稱取決於瀏覽器。謝謝你的提示。 – 2012-03-10 22:24:42