Skip to main content
Participant
January 29, 2021
Answered

How to stop sound on keydown?

  • January 29, 2021
  • 1 reply
  • 312 views

 

I'm trying to create a mechanic where Spacebar is pressed down, a sound will play. The sound will continue to play while the spacebar is down. The sound should stop when the spacebar is not pressed. The problem I'm having is that when the spacebar is held down another instance of the audio will play over the existing one. Causing an overlapping and additional audio file being played. Help?

 

//Spacebar down

 

window.addEventListener("keydown", function(e){
this.instance = createjs.Sound.play("Long");
});

 

 

//Spacebar up

The audio file will stop if it's held down for a short period of time. If the spacebar is continuously being held, another instance of the audio starts playing.

 

window.addEventListener("keyup", function(e){
this.instance.stop();
});

 

    This topic has been closed for replies.
    Correct answer kglad

    this.restart;

     

    window.addEventListener("keydown", function(e){
    if(!this.restart){
    this.instance = createjs.Sound.play("Long");
    this.restart=true;
    }
    });
    window.addEventListener("keyup", function(e){
    this.restart = false;
    this.instance.stop();
    });

     

     

    1 reply

    kglad
    Community Expert
    kgladCommunity ExpertCorrect answer
    Community Expert
    January 29, 2021

    this.restart;

     

    window.addEventListener("keydown", function(e){
    if(!this.restart){
    this.instance = createjs.Sound.play("Long");
    this.restart=true;
    }
    });
    window.addEventListener("keyup", function(e){
    this.restart = false;
    this.instance.stop();
    });