抓住这个事件有些麻烦。 有:
<div id="click_me"></div>
<audio class="fo_audio">
<source src="track1.mp3" type="audio/mpeg; codecs='mp3'">
</audio>
<audio class="fo_audio">
<source src="track2.mp3" type="audio/mpeg; codecs='mp3'">
</audio>
<audio class="fo_audio">
<source src="track3t.mp3" type="audio/mpeg; codecs='mp3'">
</audio>
并尝试做smth:
song_number = 0;
$("#click_me").click(function(){
$("audio").get(song_number).play()
});
$("audio").get(song_number).ended(function(){
song_number++;
$("audio").get(song_number).play();
});
如何运作?
答案 0 :(得分:2)
您的代码仅为第一个音频片段分配ended()
处理程序。试试这个:
var count = $("audio").size();
$("audio").each(function (song_number) {
if (song_number < count-1) {
this.ended(function () {
$("audio")[song_number+1].play();
});
}
});
这是未经测试的。它遍历每个音频剪辑,并附加将开始播放下一个剪辑的ended()
事件。最后一个剪辑没有获得事件处理程序。
答案 1 :(得分:0)
在玩了一会儿后我最终得到了这个:
HTML:
<audio class="fo_audio" controls="controls">
<source src="http://cache.gizmodo.com/assets/resources/mp3/Woman64.mp3" type="audio/mpeg" />
<source src="http://cache.gizmodo.com/assets/resources/mp3/WomanWAV.wav" type="audio/wav" />
</audio>
<audio class="fo_audio" controls="controls">
<source src="http://cache.gizmodo.com/assets/resources/mp3/FeelGood64.mp3" type="audio/mpeg" />
<source src="http://cache.gizmodo.com/assets/resources/mp3/FeelGoodWAV.wav" type="audio/wav" />
</audio>
<audio class="fo_audio" controls="controls">
<source src="http://cache.gizmodo.com/assets/resources/mp3/Carmen64.mp3" type="audio/mpeg" />
<source src="http://cache.gizmodo.com/assets/resources/mp3/CarmenWAV.wav" type="audio/wav" />
</audio>
<div>
<button class="play" data-which="0">Play 0</button>
<button class="play" data-which="1">Play 1</button>
<button class="play" data-which="2">Play 2</button>
<button class="play" data-which="all">Play all</button>
</div>
使用Javascript:
var playing = false;
function playCascade(e) {
if(playing) { return; }
var song_number = e.song_number || 0;
var $a = $("audio").eq(song_number);
if($a.length) {
$a.get(0).play();
$a.off('ended').on('ended', function(){
playing = false;
if(e.continu) {
playCascade($.extend(e, {
'song_number': song_number + 1
}));
}
});
playing = true;
}
else {
playing = false;
}
}
$(".play").on('click', function(e) {
var which = $(this).data('which');
playCascade($.extend(e, {
'song_number': Number($(this).data('which')) || 0,
'continu': which == 'all'
}));
});
<强> DEMO 强>
注意:
e
已扩展为传递自定义数据。controls="controls"
标记中删除<audio>
。以下是代码的变体:http://jsfiddle.net/bbPCk/3/
答案 2 :(得分:0)
答案是:
var count = $("audio").length;
$("audio").each(function (song_number) {
if (song_number < count-1) {
this.addEventListener("ended", function () {
$("audio")[song_number+1].play();
});
}
});
答案 3 :(得分:0)
我还认为事件“结束”工作得很糟糕。不使用removeEventListener是边缘效应(考虑到我的上下文)。 因此,请注意:如果删除AudioElement,请不要忘记删除相关的已安装事件处理程序。