【发布时间】:2012-03-10 20:53:50
【问题描述】:
我正在创建自己的能够处理播放列表的 HTML5 音频播放器。我创建了一个自定义 myPlaylist 对象,其中包含所有 play()、pause()、stop() 和其他需要的功能。这一切正常,但此外,我需要知道音频文件何时结束才能自动开始播放下一个。
这是我正在使用的代码的相关部分:
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 也不起作用。
所以,我现在基本上一无所知,有人知道我做错了什么吗?提前致谢。
哦,我已经在 Mac OS X 的最新版 Google Chrome 和 Safari 中测试了所有这些。
编辑按照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()。
我不知道我还能尝试什么...任何额外的信息将不胜感激,谢谢!
【问题讨论】:
-
Chrome 和 Safari 中的事件名称通常不是以 on 开头(如在 audio.onended 中),在我看来更像 IE。您是否为第二个示例尝试过 audio.ended?
-
是的,我也尝试过,结果相同,但未显示警报。但我不知道事件名称取决于浏览器。感谢您的提示。
标签: javascript jquery html html5-audio