0

In my snake game i have an audio tag which plays sfx. When a peice of food gets eaten, it will play the "Food" sound below. It will then spawn a new food and if its one worth 200 points, it will make a sound called "Food 200". Problem is, as it spawns instantly after, the "Food200" audio will load while the "Food" audio is still playing/ loading giving this error

if (Audio == "Food") {
var audio = document.getElementById('SFX');
audio.src = 'audio/Food.mp3';
audio.load();
audio.play();
}

if (Audio == "Food200") {
var audio = document.getElementById('SFX');
audio.src = 'audio/Food200.mp3';
audio.load();
audio.play();
}

I have tried to "$("SFX").remove();" on my audio tag and also tried pause it but that doesnt work im still getting the error, is there a better way to do this?

user2267175
  • 595
  • 5
  • 14
Rachel Dockter
  • 946
  • 1
  • 8
  • 21

2 Answers2

1

If you need to allow several sound effects at the same time, i'd suggest making a audio tag for each audio file, e.g;

//Js
if (Audio === "Food") {
  audioFood.play();
}

if (Audio === "Food200") {
  audioFood200.play();
}

//HTML
<audio id="audioFood" src="./audio/Food.mp3"></audio>
<audio id="audioFood200" src="./audio/Food200.mp3"></audio>

Another option, if you only want a single audio tag, would be to make a "timeout" timestamp, and everytime you play a sound effect, check it & update;

var audioTimeout = +new Date(); // +new turns the date into a MS timestamp.

if (Audio === "Food") {

  var dateNow = +new Date(); 
   if(audioTimeout - dateNow > 0) return;
   else audioTimeout = dateNow + (Food.mp3 length in MS);

  var audio = document.getElementById('SFX');
  audio.src = 'audio/Food.mp3';
  audio.load();
  audio.play();
}
user2267175
  • 595
  • 5
  • 14
0

First, this is not a good idea to use a variable called Audio, it's already used by the window.Audio constructor.

Then, the error you get in the console is not that important. It is actually a chrome bug in their recent implementation of Audio.play() which now does return a Promise according to WHATWG specs (W3C has not followed yet).

FireFox 54+ also supports this now, and they don't have this bug : the error should not fire in the console if you haven't catched the returned Promise.

So you're actually good to go.

Now, of course, making a new request at high rate is not a good idea, so user2267175's advice to create multiple Audio elements is indeed a good advice. You could even have better performance by using the WebAudio API. Here is a previous post about it.

Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285