How to Fade Volume in Howler.js
This article explains how to smoothly fade the volume of audio using
the howler.js JavaScript library. You will learn how to use the built-in
.fade() method to create fade-in and fade-out effects,
customize the transition duration, and trigger actions once a fade
effect completes.
The .fade() Method
Howler.js provides a built-in .fade() method that allows
you to transition the volume of a sound from one level to another over a
specified duration.
Syntax
sound.fade(from, to, duration, [id]);from(Number): The starting volume (between0.0and1.0).to(Number): The target volume (between0.0and1.0).duration(Number): The length of the fade in milliseconds.id(Number, optional): The specific sound instance ID. If omitted, the fade applies to all active instances of the sound.
Code Examples
First, initialize your sound object:
const sound = new Howl({
src: ['audio.mp3']
});
// Play the sound
sound.play();1. How to Fade In a Sound
To fade a sound in from silence to full volume over 2 seconds (2000 milliseconds):
sound.fade(0.0, 1.0, 2000);2. How to Fade Out a Sound
To fade a sound out from full volume to complete silence over 3 seconds (3000 milliseconds):
sound.fade(1.0, 0.0, 3000);Handling the Fade End Event
You can trigger a callback function immediately after a fade completes. This is useful for pausing or stopping a track once it has completely faded out.
// Fade out over 2 seconds
sound.fade(1.0, 0.0, 2000);
// Stop the playback once the fade is finished
sound.once('fade', function() {
sound.stop();
console.log('Fade complete, sound stopped.');
});