停止音频循环Javascript

时间:2017-02-15 11:25:57

标签: javascript jquery loops audio

我有以下代码:

   var player = document.createElement('audio');
player.src = 'https://dl.dropbox.com/u/7079101/coin.mp3';
player.preload = 'auto';

   var url= 'http://www.businessdictionary.com/definition/update.html';

window.setInterval(function(){
  if($("*:contains(Update')").length > 0){
    console.log('New Update, playing sound...');
    player.play();
  }
}, 5000);
  

致谢:Laurens Swart

代码效果很好,但音频循环永远。有没有办法让音频播放一次?

2 个答案:

答案 0 :(得分:0)

您正在使用window.setInterval这将永远重复拨打player.play(),直到您拨打clearInterval()

如果您希望播放器仅播放一次,我建议您改为使用window.setTimeout

var player = document.createElement('audio');
player.src = 'https://dl.dropbox.com/u/7079101/coin.mp3';
player.preload = 'auto';

   var url= 'http://www.businessdictionary.com/definition/update.html';

window.setTimeout(function(){
  if($("*:contains(Update')").length > 0){
    console.log('New Update, playing sound...');
    player.play();
  }
}, 5000);

答案 1 :(得分:0)

您需要删除setinterval才能播放音频一次 并将音频的循环属性添加到false

试试这个:

var player = document.createElement('audio');
player.src = 'https://dl.dropbox.com/u/7079101/coin.mp3';
player.preload = 'auto';
player.loop = false;
var url = 'http://www.businessdictionary.com/definition/update.html';

// window.setInterval(function () {
        if ($("*:contains(Update')").length > 0) {
            console.log('New Update, playing sound...');
            player.play();
        }
// }, 5000);