Skip to main content

fadeOut

Lower the volume of a playing sound over a number of seconds. Set stopAfterFade to stop it once the fade reaches silence.

fadeOut(id: string, duration?: number, startVolume?: number, endVolume?: number, stopAfterFade?: boolean, skipDispatchEvent?: boolean): void;

Parameters​

ParameterTypeDefaultDescription
idstringrequiredID of the sound or stream.
durationnumberfadeOutDuration from the config (0.5)Length of the fade in seconds.
startVolumenumbercurrent volumeVolume to start from.
endVolumenumberfadeOutEndVolume from the play options, else 0Volume to end at.
stopAfterFadebooleanfalseStop the sound when the fade ends. Only happens when the end volume is 0.
skipDispatchEventbooleanfalseWhen true, no fade_out_completed event is dispatched.

Returns​

Nothing.

Example​

import { SoundHub } from 'soundhub';

const soundHub = new SoundHub();
await soundHub.loadSound('music', '/audio/theme.mp3');

soundHub.play('music', { loop: true });

// Fade out over 4 seconds, then stop
soundHub.fadeOut('music', 4, undefined, undefined, true);

// Or duck it to 0.2 and keep it playing
soundHub.fadeOut('music', 2, undefined, 0.2);
tip

To fade out at the end of a sound, pass fadeOutBeforeEndDuration to play in the PlayOptions.

Try it​

Try it

Fade a sound out

Idle
3 s
0.5 s8 s
Statestopped
Gain0.00

With the toggle off, the sound keeps playing at volume 0 after the fade. Watch the state.

Code
Your clicks show up here as soundhub calls

Good to know​

  • Does nothing when the sound is not playing. No error is reported.
  • A fade to 0 does not change the volume the next play() starts at: the sound plays again at the volume it had before the fade. A fade to any other volume is kept for the next play. The stored volume only changes when the fade completes. Before 6.4.0 a sound faded to 0 played almost silent the next time.
  • The volume from before the fade is remembered, so unmute and toggleMute return to it.
  • Every step dispatches volume_changed, and the end dispatches SoundEventsEnum.FADE_OUT_COMPLETED ('fade_out_completed'), followed by stopped when the sound is stopped. A running fade is replaced by a new one.
  • Works on streams from loadStream too. For an id that is not loaded, the error is logged, stored for getLastError and dispatched as an error event.

See also​