How to Use Howler.js Mute Event to Update UI

This article explains how to utilize the mute event in Howler.js to keep your application’s user interface synchronized with the audio state. You will learn how to set up listeners for both individual sounds and global audio, detect the current mute state, and update DOM elements like buttons and icons in real-time.

Listening to the Mute Event

Howler.js allows you to trigger a mute event whenever a sound’s mute state changes. You can listen to this event either on a specific sound instance (Howl) or globally across all sounds (Howler).

Method 1: Instance-Level Mute Event

To update the UI for a specific sound instance, register the mute event listener directly on the Howl object.

import { Howl } from 'howler';

const sound = new Howl({
  src: ['audio.mp3']
});

// Listen for the mute event on this specific sound
sound.on('mute', function() {
  const isMuted = sound.mute();
  updateMuteButton(isMuted);
});

Method 2: Global Mute Event

If your UI has a master mute button that affects all audio, register the event listener on the global Howler object.

import { Howler } from 'howler';

// Listen for global mute state changes
Howler.on('mute', function() {
  const isGlobalMuted = Howler.muted();
  updateMuteButton(isGlobalMuted);
});

Updating the UI Elements

Once the event listener detects a change, use a helper function to modify your HTML elements. This ensures your icons, text, or CSS classes accurately reflect whether the audio is muted or active.

Here is an example of how to update a button element based on the mute state:

function updateMuteButton(isMuted) {
  const muteBtn = document.getElementById('mute-btn');
  const icon = document.getElementById('mute-icon');

  if (isMuted) {
    muteBtn.setAttribute('aria-label', 'Unmute audio');
    icon.classList.replace('fa-volume-up', 'fa-volume-mute');
  } else {
    muteBtn.setAttribute('aria-label', 'Mute audio');
    icon.classList.replace('fa-volume-mute', 'fa-volume-up');
  }
}

Toggling the Mute State

To make the UI interactive, bind a click event to your button that toggles the Howler mute state. The mute event listener we set up earlier will automatically catch this change and handle the UI update.

const muteBtn = document.getElementById('mute-btn');

muteBtn.addEventListener('click', () => {
  // Toggle global mute state
  const currentState = Howler.muted();
  Howler.mute(!currentState);
});

By separating the toggle logic from the UI update logic, you ensure that the UI stays accurate even if the audio is muted programmatically from other parts of your application.