How to stop sound on keydown?

New Here ,
Jan 29, 2021 Jan 29, 2021

Copy link to clipboard

Copied

 

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();
});

 

Views

39

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct Answer

Adobe Community Professional , Jan 29, 2021 Jan 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(); });

Likes

Translate

Translate
Adobe Community Professional ,
Jan 29, 2021 Jan 29, 2021

Copy link to clipboard

Copied

LATEST

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();
});

 

 

Likes

Translate

Translate

Report

Report
Community Guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines