0

I want to add a button to play one of my soundfiles randomly. The problem is that I don't want to embed the audios in any variable, because this would be a lot of work to do.

Is it possible to maybe use "document.getElementsByTagName('audio')" to play the sounds?

BIG THANKS for your help.

cut from my html:


<a onClick="randomBtn()"></a>

<a class="buttonSB" onclick="document.getElementById('audiofile1').play();">
  <audio id="audiofile1" src="url/to/soundfile1.mp3"></audio>
</a> 

<a class="buttonSB" onclick="document.getElementById('audiofile2').play();">
  <audio id="audiofile2" src="url/to/soundfile2.mp3"></audio>
</a> 

<a class="buttonSB" onclick="document.getElementById('audiofile3').play();">
  <audio id="audiofile3" src="url/to/soundfile3.mp3"></audio>
</a> 
        



Dustin
  • 3
  • 1
  • [Pick a random element](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) from the collection returned by `document.getElementsByTagName('audio')`. – Ivar Jul 25 '22 at 13:27

1 Answers1

0

I hope it would work for you. I didn't check it.

var s_files = document.getElementsByClassName('buttonSB')
  function randomBtn(){
    s_files[Math.floor(Math.random() * s_files.length)].click();
  }