0

I have this sound:

a = new Audio('audio.mp3');

and when I want to play it I use a.play() How can I play this at random times?

2 Answers2

2

Try this:

(function loop() {
    var rand = Math.round(Math.random() * (3000 - 500)) + 500; // A random value between 3 and 500 seconds

    setTimeout(function() {
            a.play(); // Play the audio
            loop(); // Call the loop function again
    }, rand);
}());

Source: this question.

Community
  • 1
  • 1
squill25
  • 1,198
  • 6
  • 20
0

setInterval and Math.random() are what you are looking for.

a = new Audio('audio.mp3');
window.setInterval(function () {
    a.play();
}, Math.random() * 500);