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.
CodePudding user response:
I think you want something like this:
- Place your audio source as strings in an array, coupled with other info, ( you mentioned questions );
- Iterate the array and build the DOM nodes, placing an event listener on click or any other event you want to trigger the sound;
- Just add the audio source to the html audio node dinamically when the event occurs and play it;
const data = [{
text: "Alastair Culham",
audio: "https://upload.wikimedia.org/wikipedia/commons/7/7f/Alastair_Culham_voice.ogg"
}, {
text: "Bill Tomphson",
audio: "https://upload.wikimedia.org/wikipedia/commons/b/b1/Bill_Thompson_speaking.ogg"
}]
data.forEach(d => {
const btn = document.createElement("button")
btn.innerText = d.text
btn.onclick = () => {
audio.src = d.audio
audio.play()
}
root.appendChild(btn)
})
<div id="root"></div>
<audio id="audio">
CodePudding user response:
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.