0

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.

corsairer
  • 3
  • 3

1 Answers1

0

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>
Mad7Dragon
  • 1,237
  • 1
  • 10
  • 21