2014-03-18 57 views
5

我尝试了下面的代码,在某些时候播放JavaScript中的声音但没有成功,声音只播放一次,这是什么问题?如何在JavaScript中循环声音?

for(var i = 0; i < errors; i++){ 
    PlaySound3(); 
} 

功能:

function PlaySound3() { 
    var audioElement = document.getElementById('beep'); 
    audioElement.setAttribute("preload", "auto"); 
    audioElement.autobuffer = true;  
    audioElement.load(); 
    audioElement.play(); 
}; 

HTML代码:

<audio id="beep"> 
    <source src="assets/sound/beep.wav" type="audio/wav" /> 
</audio> 
+0

我认为基本上是你AREN”等待声音完成。 for循环运行速度非常快,您只能听到最后一个。尝试在“PlaySound”之后稍稍等待或使用事件来检测播放完成时。 –

+0

你的建议是什么?如何在声音之间延迟? – user3427977

回答

5

如果你想播放的声音无限使用的标签音频属性loop

<audio id="beep" loop> 
    <source src="assets/sound/beep.wav" type="audio/wav" /> 
</audio> 

编辑

如果你想经过3次停止循环,添加事件侦听器:

HTML:

<audio id="beep"> 
    <source src="assets/sound/beep.wav" type="audio/wav" /> 
</audio> 

JS:

var count = 1 
document.getElementById('beep').addEventListener('ended', function(){ 
    this.currentTime = 0; 
    if(count <= 3){ 
     this.play(); 
    } 
    count++; 
}, false); 
+0

我想循环声音只是某些时间不是永远 – user3427977

+0

当你想停止循环,用javascriptp将属性'loop'改为false。 – R3tep

+0

好主意,但如何做到这一点? – user3427977