Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

How to stop sound on keydown?

New Here ,
Jan 29, 2021 Jan 29, 2021

 

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

 

271
Translate
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

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

 

 

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

 

 

Translate
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