How to Implement a Volume Ramp in Howler.js
Implementing a volume ramp, or fade effect, in howler.js is a
straightforward process thanks to the library’s built-in audio control
methods. This article explains how to smoothly transition audio volume
up or down using the native .fade() function, complete with
practical code examples to integrate into your web projects.
To implement a volume ramp in howler.js, you use the
.fade() method. This function transitions the volume of a
sound from one level to another over a specified duration.
The .fade() Method
Syntax
The syntax for the fade method is:
sound.fade(from, to, duration, [id]);from(Number): The starting volume (0.0 to 1.0).to(Number): The ending volume (0.0 to 1.0).duration(Number): The duration of the ramp in milliseconds.id(Number, optional): The specific sound instance ID to fade. If omitted, it affects all playing instances of theHowlobject.
Example: Volume Ramp Up (Fade In)
To ramp the volume up from silence to full volume when a sound starts playing, use the following code:
// Initialize the sound
const sound = new Howl({
src: ['track.mp3'],
volume: 0 // Start at 0 volume
});
// Play the sound
sound.play();
// Ramp the volume from 0 to 1 over 3000 milliseconds (3 seconds)
sound.fade(0, 1, 3000);Example: Volume Ramp Down (Fade Out)
To ramp the volume down to silence (for example, when pausing or stopping a track), you can transition the volume from its current level to zero:
// Ramp the volume from 1 to 0 over 2000 milliseconds (2 seconds)
sound.fade(1, 0, 2000);Handling the Fade Completion Event
Howler.js fires a fade event when the volume ramp
finishes. You can listen for this event to trigger subsequent actions,
such as pausing the audio after a fade-out is complete.
// Fade out over 2 seconds
sound.fade(1, 0, 2000);
// Pause the sound once the fade-out completes
sound.once('fade', () => {
sound.pause();
console.log('Fade complete, sound paused.');
});