Why this code is not Playing an Audio?

I’m working on Simon Game and I want to make an error sound when the player click on the wrong button. So, the lines which make the error sound are:

var audioError = playAudio(5);
setTimeout(stopAudio(audioError), 2000);

Where the functions playAudio and stopAudio are:

function playAudio(n) {
  var strAudio = "audio" + n;
  var audio = document.getElementById(strAudio);
  audio.loop = true;
  audio.play();
  
  return audio;
}

function stopAudio(audio) {
  audio.loop = false;
  audio.pause();
}

My audios I put on audio tags in html, like this one:

<audio id="audio5">
  <source src="https://res.cloudinary.com/kurt-johnson/video/upload/v1491432845/simon1_ppd3st.mp3" type="audio/mpeg">
</audio>

When I delete the second line [ setTimeout(stopAudio(audioError), 2000); ] the audio is played, but it is not stopped! So, why the first code above is not playing an Audio when with the second line?

You will have to wrap stopAudio(audioError) inside an anonymous function, because now you are directly calling it.

Basically playAudio() and stopAudio() both run, but directly after each other.

1 Like

It worked now! Thanks!

( I didn’t understand very well why it worked, but no problem… )

This is more of a hack of a solution, but I thought I would show it. If you know the duration of the audio clip and just want to play the last x number of seconds of it you could use the following. I used your audio file which was ~10 seconds in length and started playing it at the 8 second mark. I will see if I can figure out a way to play only the first 2 seconds of the clip with the same line of thinking.

var audioError = playAudio(5); 

function playAudio(n) {
  var strAudio = "audio" + n;
  var audio = document.getElementById(strAudio);
  audio.currentTime = 8;
  audio.play();
}
2 Likes