如何在JavaScript中循环声音? [英] How to loop sound in JavaScript?
本文介绍了如何在JavaScript中循环声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了下面的代码,在某些时候播放JavaScript中的声音,但没有成功,声音只播放一次,是什么问题?
for(var i = 0; i PlaySound3();
$ / code>
功能:
函数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.wavtype =audio / wav/>
< / audio>
解决方案
如果您想播放声音,在标签音频中 loop
:
< audio id =beeploop>
< source src =assets / sound / beep.wavtype =audio / wav/>
< / audio>
编辑
如果您想在3次后停止循环,请添加一个事件侦听器:
HTML:
< audio id =beep>
< source src =assets / sound / beep.wavtype =audio / wav/>
< / audio>
JS:
var count = 1
document.getElementById('beep')。addEventListener('ended',function(){
this.currentTime = 0;
if(count< ; = 3){
this.play();
}
count ++;
},false);
I tried below code to play a sound in JavaScript for certain times but with no success, the sound plays just once, what is the problem?
for(var i = 0; i < errors; i++){
PlaySound3();
}
Function:
function PlaySound3() {
var audioElement = document.getElementById('beep');
audioElement.setAttribute("preload", "auto");
audioElement.autobuffer = true;
audioElement.load();
audioElement.play();
};
HTML code:
<audio id="beep">
<source src="assets/sound/beep.wav" type="audio/wav" />
</audio>
解决方案
If you want to play the sound infinitely use the attribute loop
in the tag audio :
<audio id="beep" loop>
<source src="assets/sound/beep.wav" type="audio/wav" />
</audio>
Edit
If you want to stop the loop after 3 times, add an event listener :
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);
这篇关于如何在JavaScript中循环声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文