0

I did a magic 8 ball for practice with JavaScript, and then someone told me if I could link the answers with an audio file that says exact the same that is displayed. I've been searching the web and I couldnt find an answer.

I don't know how to link a Math.random list of the answers with the audio file. Any idea would be highly appreciated.

Peter O.
  • 32,158
  • 14
  • 82
  • 96

1 Answers1

0

Let's say your answers are organized in a Javascript array. For example.

const answers = ['yes', 'no', 'unknown']

and you look up an answer something like this

let answer = answers[Math.floor(Math.random() * answers.length]

Then, let's say your audio files have names like 'yes.mp3' and so on.

So, change your answers array like this, to include both the text and audio. Make it an array of two-element arrays.

const answers = [ ['yes', 'yes.mp3'], ['no', 'no.mp3], ['unknown', 'unknown.mp3]] 
let answerItem = answers[Math.floor(Math.random() * answers.length]
let answer = answerItem[0]
let answerAudio = answerItem[1]

The trick to this is to understand that arrays can contain many kinds of objects.

Once you have figured out how to get the names of your audio files, the next step will be to figure out how to play them. Don't hesitate to ask another question if the intertoobz don't help you figure that out.

O. Jones
  • 103,626
  • 17
  • 118
  • 172