3

So for my website, I want to make it so if you load the page, a javascript block will generate a random number 1-5 and depending on the number generated, it will play an audio file. Such as something like this in Visual Basic but into JavaScript code:

Generate a random number between 1-5, so that 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 back. I do appreciate it. :)

Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41
Doggy
  • 33
  • 5

2 Answers2

3
(new Audio("somefolder/song"+(Math.floor(Math.random()*5)+1)+".mp3")). play();
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
2
random_number = Math.ceil(Math.random()*5)
var audio = new Audio('song'+random_number+'.mp3');
audio.play();
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118