Search code examples
typescriptaudiodelaypause

Pause or wait after playing audio clips


I'm trying to get a random delay of between 5 to 10 seconds after an audio file has been played but it won't work and I can't figure out what's wrong. I've tried everything from setTimeout to setInterval.

I just want this to play random audio files with random delays between the given time.

Is there a simpler way?

<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>

Solution

  • The typical approach to waiting in JS is to resolve a promise after some delay created by setTimeout, then chain your logic on it:

    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>