循环播放音频次数有限

时间:2019-12-03 03:39:53

标签: javascript html audio html5-audio mediaelement

我正在尝试在特定条件下在Web浏览器中播放音乐,threshold = true进行了10次迭代,这是我的代码:

<script>
var threshold = true;
for (var i=0 ; i<10; i++){// number of iteration
    if ( threshold){
          var audio = new Audio('song.mp3');
          audio.play();
    } 
}
</script>

在我没有任何错误的情况下,歌曲不会在浏览器中播放;因此,我不知道什么可能是错误的。

1 个答案:

答案 0 :(得分:0)

首先,除非您要立即响应某种用户操作,否则通常无法调用audio.play()。这是由于autoplay policy

接下来,我将循环留给浏览器:

audio.loop = true;

现在,使用seeked事件来确定音频何时返回。 (很可能会循环。)发生这种情况时,请增加循环计数。然后,看看我们是否循环了太多次,如果循环了,则暂停一下。

 let maxLoops = 10;
 let lastTime = 0;
 let loops = 0;
 audio.addEventListener('seeked', (e) => {
   if (e.target.currentTime < lastTime) {
     loops++;
   }
   if (loops >= maxLoops) {
     e.target.pause();
   }
   lastTime = e.target.currentTime;
 });