0
submitQuizButton.addEventListener("click", function  () {
        showFinalPage();

 }); 

I would like to implement an audio file within this button, but i've no clue how to write the code for it. Anyone has a link or can explain to me how this works?

3 Answers3

1

Hope this helps

<!DOCTYPE html>
<html>
<body>

<audio id="myAudio">
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

<p>Click the buttons to play or pause the audio.</p>

<button onclick="playAudio()" type="button">Play Audio</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button> 

<script>
var x = document.getElementById("myAudio"); 

function playAudio() { 
  x.play(); 
} 

function pauseAudio() { 
  x.pause(); 
} 
</script>

</body>
</html>
0

Without using html

var audio = new Audio('audio.mp3');

submitQuizButton.addEventListener("click", function  () {
    showFinalPage();
    audio.play();
});

More info can be found at: https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement

SamNewton
  • 72
  • 5
  • that didn't work for me, ``` var audio = new Audio('SuperMarioBros.mp3'); submitQuizButton.addEventListener("click", function () { showFinalPage(); }); ``` – christiaan rosner Oct 09 '19 at 19:10
  • I forgot a line, my apologies. – SamNewton Oct 09 '19 at 19:11
  • NotAllowedError: The play method is not allowed by the user agent or the platform in the current context, possibly because the user denied permission. This is the error i've been receiving if i inspect it. – christiaan rosner Oct 09 '19 at 19:19
  • https://jsfiddle.net/vth3mu5n/ It's working for me. In Chrome, the user has to do an action before audio can be played, which is what is happening in this case. It could be a local permissions issue of playing audio. Does it work in other browsers for you? – SamNewton Oct 09 '19 at 19:35
  • I've had a similar issue before when the file of a background, refused to work but a link online did. You reckon I should give that a shot? I fixed it! It worked! Apparently there was something within my code preventing it, thanks for the help!! – christiaan rosner Oct 09 '19 at 19:43
0

This could work

<script>
    submitQuizButton.addEventListener("click", function  () {
        var audio = document.getElementById("audio");
        audio.play();
    });
</script>

<audio id="audio" src="src_here" ></audio>
jchung
  • 903
  • 1
  • 11
  • 23