How to Implement Audio Ducking in Howler.js
This article provides a straightforward guide on how to implement audio ducking in Howler.js. Audio ducking is the process of temporarily reducing the volume of background audio when a primary sound, such as character speech, is played. You will learn how to use Howler’s built-in fade methods and event listeners to automatically lower and restore background music levels, ensuring your dialogue remains clear and intelligible.
Understanding Audio Ducking
In game development and multimedia applications, audio ducking
prevents background music (BGM) from overpowering voiceovers or
character dialogue. Howler.js does not have a native “ducking” node, but
you can easily achieve this effect by utilizing its .fade()
method alongside event handlers like onplay and
onend.
Step-by-Step Implementation
To implement audio ducking, you need to set up two main audio sources: the background music and the voiceover. When the voiceover starts playing, you fade the music down. When the voiceover finishes, you fade the music back to its original volume.
Here is the complete JavaScript code to achieve this:
// 1. Initialize the background music
const backgroundMusic = new Howl({
src: ['background-music.mp3'],
loop: true,
volume: 0.8 // Default volume
});
// Start playing the background music
backgroundMusic.play();
// 2. Initialize the character speech audio
const characterSpeech = new Howl({
src: ['character-speech.mp3'],
volume: 1.0, // Speech plays at full volume
// Triggered when the speech starts playing
onplay: function() {
// Duck the background music from 0.8 to 0.2 over 300 milliseconds
backgroundMusic.fade(0.8, 0.2, 300);
},
// Triggered when the speech finishes playing
onend: function() {
// Restore the background music from 0.2 to 0.8 over 500 milliseconds
backgroundMusic.fade(0.2, 0.8, 500);
},
// Triggered if the speech is manually stopped or interrupted
onstop: function() {
backgroundMusic.fade(backgroundMusic.volume(), 0.8, 500);
}
});
// 3. Trigger the speech (for example, on a button click or game event)
function speakCharacter() {
characterSpeech.play();
}How the Code Works
- The
fadeMethod: Thefade(from, to, duration, [id])method is the core of this implementation. It smoothly transitions the volume of the specified sound from the starting volume to the target volume over a set duration (in milliseconds). - The
onplayEvent: As soon ascharacterSpeech.play()is called, theonplaycallback triggers. This initiates a 300ms fade that lowers the background music to a quiet level (0.2), making the speech easy to hear. - The
onendEvent: Once the speech audio file reaches its end, theonendcallback triggers. This fades the background music back up to its original volume (0.8) over 500ms. - The
onstopEvent: If the dialogue is interrupted or skipped, theonstopcallback ensures that the background music is restored to its normal volume, preventing the music from getting stuck at a low level.