播放音频剪辑后暂停或等待

Pause or wait after playing audio clips

我试图在音频文件播放后获得 5 到 10 秒的随机延迟,但它不起作用,我也不知道出了什么问题。我已经尝试了从 setTimeoutsetInterval 的所有方法。

我只想让它在给定时间之间以随机延迟播放随机音频文件。

有没有更简单的方法?

<body style="background-image: url(image/funky.gif)">
<audio id="myaudio" controls="controls" autoplay="autoplay">
</audio>
<script type="text/javascript">
    var sounds = new Array();
    sounds[0]="https://plplatoon.com/homebrew/wav/2.mp3";
    sounds[1]="https://plplatoon.com/homebrew/wav/3.mp3";
    sounds[2]="https://plplatoon.com/homebrew/wav/5.mp3";   
    sounds[3]="https://plplatoon.com/homebrew/wav/7.mp3";
    sounds[4]="https://plplatoon.com/homebrew/wav/Zombie Back From Dead.mp3";
    sounds[5]="https://plplatoon.com/homebrew/wav/Zombie-Aggressive-Attack-A9.wav";
    sounds[6]="https://plplatoon.com/homebrew/wav/zombie-growl.mp3";
    sounds[7]="https://plplatoon.com/homebrew/wav/zombie-monster-beast.mp3";
    sounds[8]="https://plplatoon.com/homebrew/wav/zombie-walk.mp3";

    function getRandomSounds() {
        var randomNum = Math.floor(Math.random() * sounds.length);
        document.getElementById("myaudio").src = sounds[randomNum];
        yield return new WaitForSeconds(Random.Range(5,10));
              GetComponent<AudioSource>().Play();
    
    }
    document.getElementById("myaudio").addEventListener("ended", getRandomSounds);
    getRandomSounds();
</script>
</body>

在 JS 中等待的典型方法是在 setTimeout 造成的一些延迟后解决承诺,然后将您的逻辑链接到它上面:

const wait = ms =>
  new Promise(resolve => setTimeout(resolve, ms))
;
const rand = (lo, hi) => ~~(Math.random() * (hi - lo)) + lo;

const baseURL = "https://plplatoon.com/homebrew/wav/";
const sounds = [
  "2.mp3", "3.mp3", "5.mp3", "7.mp3",
  "Zombie Back From Dead.mp3",
  "Zombie-Aggressive-Attack-A9.wav",
  "zombie-growl.mp3",
  "zombie-monster-beast.mp3",
  "zombie-walk.mp3",
].map(e => baseURL + e);

const playRandomSound = () => {
  audioEl.src = sounds[rand(0, sounds.length)];
};

const audioEl = document.querySelector("audio");
audioEl.addEventListener("ended", async () => {
  await wait(rand(5000, 10000));
  playRandomSound();
});
playRandomSound();
<audio id="myaudio" controls="controls" autoplay="autoplay">
</audio>