Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中随机播放声音_Javascript - Fatal编程技术网

如何在javascript中随机播放声音

如何在javascript中随机播放声音,javascript,Javascript,我有这样的声音: a = new Audio('audio.mp3'); 当我想玩它时,我使用a.play() 我如何在随机时间播放此内容?试试以下方法: (function loop() { var rand = Math.round(Math.random() * (3000 - 500)) + 500; // A random value between 3 and 500 seconds setTimeout(function() { a.pl

我有这样的声音:

a = new Audio('audio.mp3');
当我想玩它时,我使用
a.play()
我如何在随机时间播放此内容?

试试以下方法:

(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);
}());

来源:问题。

setIntervalMath.random()是您需要的

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