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