I am trying to make an audio file play on my html page (I can get it to play using onclick). But, I am trying to play an audio clip when a specific text is displayed. For instance, I am trying to play an audio clip that needs to be specific to the displayed text (or whatever object).
So, I have some strings (Questions and Answers) but I can't figure out what to assign to the strings to trigger the audio file to play. Also, maybe there's another way by just making a function for each question.
I think you want something like this:
const data = [{
question: "What's the name of Culham?",
choices: ["Alan", "Alastair"],
answer: "Alastair",
audio: "https://upload.wikimedia.org/wikipedia/commons/7/7f/Alastair_Culham_voice.ogg"
}, {
question: "What's the name of Thompson?",
choices: ["Bill", "John"],
answer: "Bill",
audio: "https://upload.wikimedia.org/wikipedia/commons/b/b1/Bill_Thompson_speaking.ogg"
}]
const generate = () => {
root.innerHTML = ""
audio.src=""
const idx = Math.round(Math.random() * (data.length - 1))
root.innerHTML += `<div>${data[idx].question}</div>`
data[idx].choices.forEach(c => {
const btn = document.createElement("button")
btn.innerText = c
btn.onclick = function() {
if (data[idx].answer === c) {
audio.src = data[idx].audio
audio.play()
audio.onended = generate
} else alert("Wrong Answer, try again")
}
root.appendChild(btn)
})
}
generate()
reset.onclick = generate
<div id="root"></div>
<audio id="audio"></audio>
<button id="reset">Reset</button>
Don't put your questions in one place and the audio cues in another. Keep them together in data objects that have properties per question. For example:
questions = [
{
question: 'What is your quest?',
answer: 'To seek the holy grail.',
badAnswers: [
'16.9 Gigawatts',
'African or European?',
'Red. No, blue!'
],
audioQuestion: 'hmm.mp3',
audioCorrect: 'youtu.be/0D7hFHfLEyk',
audioIncorrect: 'sproing.mp3'
},
{
question: 'My milkshake brings more boys to the _____.',
answer: 'yard',
badAnswers: [
'stand',
'steps',
'park',
'21st century'
],
audioQuestion: 'hmm.mp3',
audioCorrect: 'youtu.be/i4YutyVP7ig',
audioIncorrect: 'sproing.mp3'
}
]
And then you can have a function that knows what to do when given an element of this array.