60秒后停止音频没有循环 - Javascript

时间:2017-11-30 11:58:24

标签: javascript

所以我有10秒的音频,但我想在页面内60秒后停止选项重播,我不希望音频循环。但是音频会循环到5。

var iterations = 1;

            document.getElementById('iteration').innerText = iterations;

                if (iterations < 5) {

                    this.currentTime = 0;
                    this.play();
                    iterations ++;

                    document.getElementById('iteration').innerText = iterations;

                }
            }, false);

1 个答案:

答案 0 :(得分:0)

您可以尝试setTimeout()在一定秒后停止音频。这是一个开始播放音频文件并在6秒后停止播放的示例。

&#13;
&#13;
document.getElementById('audioSample').play();
setTimeout(function() {
  document.getElementById('audioSample').pause();
}, 6 * 1000); // Stops the audio player after 6 seconds
&#13;
<audio controls id="audioSample">
  <source src="http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
&#13;
&#13;
&#13;

&#13;
&#13;
let countdown = 6;

document.getElementById("audioSample").play();

let interval = setInterval(function() {
  countdown -= 1;
  document.getElementById("count").innerHTML = countdown;
  if (countdown <= 0) {
    document.getElementById("audioSample").pause();
    clearInterval(interval);
  }
}, 1000);
&#13;
<audio controls id="audioSample">
      <source src="http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
    </audio>

<div>Time left:</div>
<div id="count"></div>
&#13;
&#13;
&#13;