在html5里,如何让一个<audio>循环播放4词!
JScript code
var audio = document.createElement("audio");
audio.src = "piano/3C.mp3";
audio.addEventListener('ended', function () {
// Wait 500 milliseconds before next loop
setTimeout(function () { audio.play(); }, 500);
}, false);
audio.play();
以上代码能够让音频按5毫秒间隔循环播放,现在我只需要循环播放4次,该如何修改?
------解决方案--------------------
var audio = document.createElement("audio");
audio.src = "piano/3C.mp3";
audio.addEventListener('ended', function () {
// Wait 500 milliseconds before next loop
var index = 0;
setTimeout(function () {if(index<4){ audio.play(); index++}}, 500);
}, false);
audio.play();
这里的index必须设置为全局变量,这是个闭包问题!
var audio = document.createElement("audio");
var index = 0;
audio.src = "piano/3C.mp3";
audio.addEventListener('ended', function () {
// Wait 500 milliseconds before next loop
setTimeout(function () {if(index<4){ audio.play(); index++}}, 500);
}, false);
audio.play();