[SOLVED] Choppy Sound

Hello, all.
I am trying to make a sound that plays when the gun is shooting and then pauses or stops when it is not shooting. I added a new sound and tried pausing it when it wasn’t shooting, but the sound got really choppy. Here is my code:

if(this.app.keyboard.isPressed(pc.KEY_Q)&& this.rounds !=0 && this.timer > this.cooldown){
this.isShooting =true
this.timer = 0;
this.rounds = this.rounds -1;
this.bulletTxt.element.opacity = 1;
this.bulletTxt.element.outlineThickness = 1;
var newBullet = this.bullet.clone();
this.app.root.addChild(newBullet);
newBullet.setPosition(this.bullet.getPosition());
newBullet.enabled = true;
//alert(this.rounds);
this.timer = 0;
}else{
    this.isShooting = false;
}


if(this.isShooting === true){
        this.entity.sound.play('gunShot');

}else{
         this.entity.sound.pause('gunShot');
         //   this.entity.sound.stop('gunShot');

};

Here is the editor link if you want to try it for yourself, Q to shoot and R to reload: PlayCanvas | HTML5 Game Engine

Hi @Codeknight999!

Your sound is probably starting repeatedly.

Please try the code below.

if (this.isShooting === true) {
    if (!this.entity.sound.isPlaying('gunShot')) {
        this.entity.sound.play('gunShot');
    }
}
else {
    this.entity.sound.stop('gunShot');
}

Hi @Albertos
I tried that code and the sound just stopped. I tested other sound and they work, but the gun sound still doesnt.

I will take another look later today.

It’s hard to read your code because you don’t apply a correct code structure. If you use a correct code structure you can easily see where a function or statement start and end.

You can use the tab key on your keyboard for this.

1 Like

Let me fix that, I think playcanvas has a button to do that.

I formatted it.

1 Like

I debugged your code and the problem is that the sound is already stopped before it could be played. This is probably because there is a silence in your sound file first. You can fix this by setting a specific start time on your sound component or using a different sound file.

I checked and fixed the sound but it doesn’t play all the way through, I just made the duration 1, but it still doesn’t play right.

I just checked your project and it now seems to work as expected.

It works now. Sorry. Thanks for your help!

1 Like