简体   繁体   中英

How to get repeat function play sound more than once in JavaScript?

I have some difficulty with making script below to work as intended, which is to play sound repeatedly as in the function (repeatR). Input for the number of repetitions may come from user (button).

  var timer, start; function repeatR(callback, interval, repeats, immediate) { var timer, trigger; trigger = function() { callback(); --repeats || clearInterval(timer); }; interval = interval <= 0 ? 1000 : interval; // defaultní repeats = parseInt(repeats, 10) || 0; // loop timer = setInterval(trigger, interval); if ( !! immediate) { trigger(); } return timer; } window.run = function () { var args = Array.prototype.slice.call(arguments, 0); if( timer ) { clearInterval(timer); } start = (new Date).getTime(); document.getElementById("test").play(); } 
  <body> <div> <input type="button" value="Once after 1 sec" onclick="run(1000, 1)"> <input type="button" value="Once immediately" onclick="run(0, 1, true)"> <input type="button" value="5 times, 0.5s interval" onclick="run(500, 5)"> <input type="button" value="5 times, 0.5s interval, immediate start" onclick="run(500, 5, true)"> <input type="button" value="Forever, 1s interval" onclick="run(1000)"> <audio id="test" src="test.wav"</audio> </div> </body> 

At this time code repeat the sound only once.

I would be glad for some suggestion/solutions on this.

Thank you.

You can use Audio loop Property which is audioObject.loop = true|false

<body> 

<audio id="myAudio" controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio><br>

<button onclick="enableLoop()" type="button">Enable loop</button>
<button onclick="disableLoop()" type="button">Disable loop</button>
<button onclick="checkLoop()" type="button">Check loop status</button>

<script>
var x = document.getElementById("myAudio");

function enableLoop() { 
  x.loop = true;
  x.load();
} 

function disableLoop() { 
  x.loop = false;
  x.load();
} 

function checkLoop() { 
  alert(x.loop);
} 
</script> 

</body> 

Like the above code, for reference See W3 Schools Audio Loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM