Fade out Sound outside of its duration

Hello!

I just started using Phaser 3.

I have a sound file. Let’s say it’s 5 seconds in duration.

I immediately play the sound with:

sound.play(id, { volume: 1});

After let’s say after 3 seconds, I now want to fade out the sound:

const currentSound = sound.get(id);
this.tweens.add({
   targets: currentSound,
   volume: 0,
   duration: 1000,
});

This is great since the sound plays for 3 seconds and then fades away by 4 seconds.

However, when I increase the duration of the fade out to something beyond the sound file’s duration (say a duration of 8000), I get an error in the updateTweenData:

TypeError: Cannot set property 'volume' of null

I believe it’s because the sound has finished but the tween is still attempting to adjust its volume.

Is there a good way to guard against tween durations outside of the sound’s length?
Is there a way I can get the current “elapsed” time of the sound and adjust my tween’s duration to something within the remaining time of my sound?

Thanks!

Hi @drohrlick,
If you play the sound from the sound manager, it is destroyed on stop.
You have two options:
1 ) Listen to the sound stop event and stop the tween from the listener.

const currentSound = sound.get(id);
let tween = this.tweens.add({
   targets: currentSound,
   volume: 0,
   duration: 1000,
});
currentSound.on('stop', () => {
    tween.stop();
});

2 ) Add the sound to the scene and play it:

const mysound = this.sound.add('mysoundkey');
mysound.play(); // sound is not destroyed on stop

Good luck!

Great advice!

From the way I was using my sound, I had to make use of the ‘complete’ event instead of the ‘stop’ event. But from there, I was able to make sure the tween stops.

Thanks!