'Trouble Playing Changing Audio Files in JavaScript

So essentially I am trying to build a browser game in which various texts and audio clips are played at random, and then you must choose what language it is. I've built the base for it which functions well with just text and choosing an answer at random, but I'm having trouble adding the sound file and having it play. This is my first real project using JavaScript and I was hoping I could get some help here.

The HTML div I'm using is as follows

  <div class="field">Play Audio</div>
  <button id="audio" onclick="audio_clicked()"></button>
</div> 

then I have a seperate, linked .js file which I'm doing the following-

Storing the questions in a question bank

quiz[0] = new Question("Hola", "languages/spanish.mp3", "Spanish", "Italian", "Cyric");
quiz[1] = new Question("Hello", "languages/english.mp3", "English", "Spanish", "French");
quiz[2] = new Question("Haye", "languages/udhr_somali.mp3", "Somali", "Norwegian", "Swedish");

Reading the questions

  document.getElementById("question").innerHTML= randomQuestion.question;
  document.getElementById("audio").innerHTML=randomQuestion.audio;

and finally executing the process when the button is clicked

// play audio button clicked
function audio_clicked() {
      audio.play();
}

// what to do when answer a button clicked
function answerA_clicked() {
  var answerA = document.getElementById("answerA").value;
    checkAnswer(answerA);
}

This is where I am having the trouble, as I'm not sure it is reading my audio correctly. It started displaying the audio file name on the button which is the opposite of what i want. The full project is on my GitHub github.com/tjsanzen/language-game

Thank you for any help you may provide :)



Solution 1:[1]

If you want to play a audio with JavaScript use Audio.

function audio_clicked(url) {
      new Audio(url);
      audio.play();
}

Then change your btnProvideQuestion to handle the click event

document.getElementById("audio").onclick = function () {
    audio_clicked(randomQuestion.audio);
}

Or you can combine them.

document.getElementById("audio").onclick = function () {
    new Audio(randomQuestion.audio);
    audio.play();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prana