How to Load Audio with Howler.js

In this guide, you will learn how to load and play a basic audio file using Howler.js, a powerful JavaScript audio library. We will cover how to include the library in your project, initialize the Howl object with your audio file path, and trigger the playback using simple JavaScript commands.

Step 1: Include Howler.js in Your Project

To start using Howler.js, you need to include the library in your HTML file. You can load it directly via a CDN by adding the following <script> tag to the <head> or before the closing </body> tag of your HTML document:

<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.2.4/howler.min.js"></script>

Step 2: Initialize the Audio File

Howler.js uses the Howl constructor to load and control audio files. You need to create a new instance of Howl and pass an options object containing the path to your audio file.

Here is the basic syntax to define your audio:

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

The src property accepts an array of file paths. This allows you to provide fallback formats (such as .ogg or .wav) to ensure compatibility across all web browsers:

const sound = new Howl({
  src: ['audio/sound-effect.ogg', 'audio/sound-effect.mp3']
});

Step 3: Play the Loaded Audio

Once the Howl object is initialized, you can play the audio file by calling the .play() method.

sound.play();

Complete Code Example

Because modern web browsers often block autoplaying audio until a user interacts with the page, it is best practice to trigger the audio playback via a user action, such as clicking a button.

Below is a complete HTML and JavaScript example demonstrating how to load and play an audio file on a button click:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Howler.js Quick Start</title>
    <!-- Include Howler.js CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.2.4/howler.min.js"></script>
</head>
<body>

    <button id="playBtn">Play Sound</button>

    <script>
        // Load the audio file
        const sound = new Howl({
            src: ['audio/sound-effect.mp3'],
            html5: true // Force HTML5 Audio to handle large files and stream audio
        });

        // Play the sound when the button is clicked
        document.getElementById('playBtn').addEventListener('click', function() {
            sound.play();
        });
    </script>

</body>
</html>

Basic Audio Controls

Howler.js also provides straightforward methods to pause, stop, and adjust the volume of your loaded audio: