Entity.sound.play creating tiny lag

Hello fellow developers!

I have a script, that functions as a random shooter, which does randomly between set intervals fire a shot. Now the shot is just one Entity with a sound component and two slots, shot and impact. And whenever a shot is to be fired, the Shot sound is played and then the impact sound. I do not calculate any travel time, I simply play the two sounds.

Now on my good computer that is no problem at all. But on an okay computer it lags out my program.

Any hints on why this might happen ? Because it also lags when I only use the “Shot” sound with no impact sound. it just doesn’t lag as heavily.

The Code for the shot which is randomly fired is as simple as follows:


var Shot = pc.createScript('shot');

// initialize code called once per entity
Shot.prototype.initialize = function() {
    
};

Shot.prototype.fireShot = function(){
    
    try{
        this.entity.sound.play("Shot");
    }catch(ex){
        console.log("no Slot Shot attached");
    }
    
    this.entity.enabled = true;
       
    this.reachedImpactPoint();

};

Shot.prototype.reachedImpactPoint = function(){
    try{
        this.entity.sound.play("Impact");
    }catch(ex){
        console.log("no Slot Impact attached");
    }
   
};

Shot.prototype.destroyEntity = function(){
    this.entity.destroy();
};

Hi @Bfischlin,

Your code seems fine, two things to think about:

  • Are the sound assets preloaded? If not then when trying to play the sound will make Playcanvas fetch and then play the sound which will add lag the first time.
  • You said that first you play the shot sound and then the impact sound. In your code the reachedImpactPoint() is being called as soon as you start playing the shot sound, so I imagine the sounds start to play at the same time (if they are loaded and ready).

Hey, thanks for the reply.

Yes the audio files are already preloaded.

Yeah I know they are pretty much played simultaneously and you can hear them accordingly. In reallife you could hear the impact even before the actual shot depending on how far the shot was fired from. But as I said, it’s also lagging when I remove the “Impact” sound and only use the shot sound.

Not sure why that would happen, could you share a sample project to take a look?

Is it a WAV, MP3 or OGG file? Might be worth try WAV as it could be a decompression issue

1 Like

Sorry for the long wait. I use both filetypes.

Well I noticed, that on my “bad” laptop in the game I have about 15FPS at the time the sounds are triggered. (It’s a pretty big game and the laptop is from 2013 or something… runs with 60 FPS on newer devices), There whenever the sound is triggered it drops to like 2 FPS and then back up.

Still can’t figure out why it happens tough…