BenjaminTal
BenjaminTal

Reputation: 17

How to play a sound based on a random number

I try to play a sound file based on a result from a Math.random between 1-4. I building a "Simon Game" using JavaScript and want to play a specific sound file ( 1 of 4 based on the current flashing box). I have stored the 4 sounds file inside an object like this:

let random = Math.floor((Math.random() * 4) + 1);
let sounds = {
      box1: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"),
      box2: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"),
      box3: new Audio("https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"),
      box4: new Audio ("https://s3.amazonaws.com/freecodecamp/simonSound4.mp3")
};

How can I operate the sound based on random result?

Regards

Upvotes: 0

Views: 215

Answers (2)

Max Svidlo
Max Svidlo

Reputation: 774

At the bottom of the code just add:

sounds['box'+random].play();

Upvotes: 0

LucHermkens
LucHermkens

Reputation: 68

I think this is what you're looking for:

const random = Math.floor(Math.random() * Object.keys(sounds).length - 1);    
sounds[`box${random}`].play();

An array might better suite your use-case though, as it prevents the use of Object.keys().

Upvotes: 1

Related Questions