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

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

179

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

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

 

 

Votes

Translate

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

 

 

Votes

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