我以动态创建的顺序播放音频文件。我有以下代码,调用pop_modal()后会触发该代码:
var soundmute = 0;
function pop_modal(){
if(soundmute==0){
soundmute=1;
var playlist = "chime,token,nambari,moja,mbili,tatu,nne,tano,sita,saba,nane,tisa,nenda";
create_playlist_and_play(playlist);
$("#announce").modal({backdrop: true});
$("#announce").show();
play_queue_sounds("chime");
}
}
function create_playlist_and_play(list){
var tracks = list.split(",");
// add event listeners
for (var i = 0; i < tracks.length; i++) {
console.log(tracks[i]);
$("#sound-" + tracks[i])[0].addEventListener("ended", function playnext(){
if (i!=tracks.length-1){
console.log("played = "+tracks[i]);
play_queue_sounds(tracks[i+1]);
$("#sound-" + tracks[i])[0].removeEventListener("ended",playnext(),false);
}else{
setTimeout(hide_modal, 3000);
}
} , false);
}
}
function hide_modal(){
soundmute=0;
$("#announce").hide();
}
function play_queue_sounds(name){
var audio = $("#sound-" + name)[0];
audio.volume = audio.getAttribute("volume");
audio.play();
}
我的HTML中有这个
<audio preload="auto" id="sound-chime" volume=0.5>
<source src="/files/queue_sounds/chime.mp3"></source>
</audio>
<audio preload="auto" id="sound-token" volume=0.5>
<source src="/files/queue_sounds/token.mp3"></source>
</audio>
<audio preload="auto" id="sound-nambari" volume=0.5>
<source src="/files/queue_sounds/nambari.mp3"></source>
</audio>
我收到此错误:
Uncaught TypeError: Cannot read property 'getAttribute' of undefined
at play_queue_sounds (eval at setup (form.min.js?ver=1522838189.0:2641), <anonymous>:121:26)
at HTMLAudioElement.playnext (eval at setup (form.min.js?ver=1522838189.0:2641), <anonymous>:40:21)
另一个面临的问题是,如果我尝试将playnext函数移到父函数之外,则可以播放音频文件,但是似乎无法删除创建的事件侦听器。我觉得上面的构造可以解决事件侦听器的问题,但我无法使其正常工作。
经过一些调整后,我求助于更改为到目前为止可以正常工作的
function create_playlist_and_play(list){
var tracks = list.split(",");
// add event listeners
var i = 0;
for ( i = 0; i < tracks.length; i++) {
console.log(tracks[i]);
$("#sound-M" + tracks[i]).on("ended",{ "tracks": tracks,"i":i },playnext);
}
}
function playnext(event){
var tracks = event.data.tracks;
var i = event.data.i;
if (event.data.i!=event.data.tracks.length-1){
console.log("played = "+tracks[i]);
play_queue_sounds(tracks[i+1]);
}else{
setTimeout(hide_modal, 3000);
}
}
function pop_modal(){
if(soundmute==0){
soundmute=1;
var playlist = "chime,token,nambari,tatu,saba,tano,nenda,moja";
create_playlist_and_play(playlist);
$("#announce").modal({backdrop: true});
$("#announce").show();
play_queue_sounds("chime");
}
}
function hide_modal(){
$('audio[id^="sound-M"]').each(function () {
var old_element = this;
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
});
soundmute=0;
$("#announce").hide();
}