Search code examples
javascripthtmlrandomplayback

How can I use JavaScript to play a random audio on click?


I would like to use a div element as a button that, when clicked, plays a random audio file from a selection of files.

The threads here and here address random audio selection. From those sources, I came up with this script, which uses Math.random:

<script>
  var xaudio = [ "link1", "link2", "link3"];
        
  var randomxaudio = Math.floor(Math.random()*xaudio.length);
        
  function playx() {
    var audio = 'document.getElementById("clickx").innerHTML="<audio src=\""+randomxaudio+"\"/>"';
    audio.play();
  }
</script>

And this HTML:

<div class="button1" onclick="playx()" id="clickx">
  <audio id="randomxaudio">
  </audio>
</div>

This returns nothing on click. As I'm quite new to the whole programming thing, I don't understand JS well enough to identify what could be wrong (or right) about this approach, and I can't seem to get anything I find online to work for me. Any advice would be much appreciated.


Solution

  • make sure you have the correct links for audio files in an array, then use this function.

    function playRandomSound(){ 
        var sounds = [
           "https://assets.mixkit.co/sfx/preview/mixkit-exotic-tropical-bird-screech-24.mp3",
           "https://assets.mixkit.co/sfx/preview/mixkit-tropical-forest-bird-chirp-22.mp3",
           "https://assets.mixkit.co/sfx/preview/mixkit-cartoon-monkey-laugh-100.mp3"
          ];
         
        var soundFile = sounds[Math.floor(Math.random()*sounds.length)];
        document.getElementById("player").innerHTML="<embed src=\""+soundFile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\"/>";
    }
    <input type='button' value='Try Random Sound' onclick='playRandomSound()'/>
      <span id='player'></span>