Create a number, then play music

So, for my site, I want to do this, if you load the page, the javascript block will generate a random number 1-5 and depending on the number generated, it will play the audio file. For example, something like this in Visual Basic, but in JavaScript code:

Create a random number between 1-5, so 1, 2, 3, 4, and 5 are all possibilities. This number is intRandomNumber

If intRandomNumber = 1 Then
      Play song1.mp3
Else
End if

If intRandomNumber = 2 Then
      Play song2.mp3
Else
End if

If intRandomNumber = 3 Then
      Play song3.mp3
Else
End if

If intRandomNumber = 4 Then
      Play song4.mp3
Else
End if

If intRandomNumber = 5 Then
      Play song5.mp3
Else
End if

      

Thanks for any help. I appreciate it.:)

+3


source to share


3 answers


(new Audio("somefolder/song"+(Math.floor(Math.random()*5)+1)+".mp3")). play();

      



+3


source


random_number = Math.ceil(Math.random()*5)
var audio = new Audio('song'+random_number+'.mp3');
audio.play();

      



+2


source


Take a look at this link.

Playing audio with Javascript?

The rest of the code should be simple enough to write. Good luck.

0


source







All Articles