Simon game audio bug

Simon game audio bug
0

#1

Hi guys, I have a small problem. I wrote a function that plays the sound when you click on a specific “pad” on the game, my problem is that the sound for each pad only plays on the first time I click on the pads, when I click on the pad again there is no sound, any idea why this is happening?

  var soundRed = $("#sound-red")[0];
  var soundBlue = $("#sound-blue")[0];
  var soundYellow = $("#sound-yellow")[0];
  var soundGreen = $("#sound-green")[0];  

 $(".pad").on("click", function(){
    player.push(this.id);
    //console.log(player);

    if (this.id === "0") {
        soundRed.play();
    } else if (this.id === "1") {
        soundBlue.play();
    } else if (this.id === "2") {
        soundGreen.play(); 
    } else if (this.id === "3") {
        soundYellow.play(); 
    }
  });

codepen link: https://codepen.io/WynandT/pen/jZzYLq?editors=0010


#2

It works for me. A sound plays when pressing each pad.


#3

You could use the load method before the play method, like:

soundRed.load();
soundRed.play();

If you changed your audio element ids to the following: sound-0, sound-1, sound-2, sound-3, then you could simplify your pad click event as follows:

  $(".pad").on("click", function() {
    player.push(this.id);
    var $sound = $('#sound-' + this.id);
    $sound[0].load();
    $sound[0].play();
  });

#4

Thanks for the tip, will try that out!