Nomisoft
Menu

Audio sprites with howler.js

11th November 2016

If you've ever needed to play short sound effects on a website/web application/game then there's 2 handy tools which i'd highly recommend: Audiosprite (https://github.com/tonistiigi/audiosprite) and howler.js (https://github.com/goldfire/howler.js)

Howler.js is a great little lightweight library for playing sound using the Web Audio API with fallback to HTML 5 audio. It supports playing multiple different sound formats and enables us to create the audio equivalent of a spritesheet.

The audiosprite tool allows you to easily create a single sound file with all of your different sound clips concatenated.

In the following example we have 3 different sound effects we want to play on our page: a doorbell ringing, a car engine noise and a dog barking.

Combining Audio Files

Head over to the audiosprite github page for details on how to install audiosprite. You can then issue the following on the command line.


audiosprite --output effects -f howler source/doorbell.wav source/car.wav source/dog.wav

This will take the 3 sound files supplied and combine them into a single sound clip in a few different formats. You'll end up with an effects.ogg, effects.mp3, effects.m4a and effects.ac3 file by default. You'll also see the above outputs a json file containing the timing information needed for the next step

Playing Sound Effects

We need to include the howler.js library on our page. We can then create a new Howl instance.


var effects = new Howl({
    urls: ['effects.ogg','effects.m4a','effects.mp4','effects.ac3'],
    "sprite": {
        "doorbell": [
            0,
            1462.3582766439908
        ],
        "car": [
            3000,
            3266.802721088435
        ],
        "dog": [
            6200,
            1266.802721088435
        ]
    }
});

You'll notice the url/sprite information has been copied from the json file that audiosprite output.

To play the actual sounds we call the play function with the name of the sound effect we want to play:


effects.play('doorbell');
effects.play('car');
effects.play('dog');

There's plenty more functionality detailed on the howler.js github page such as being able to stop/pause, mute, loop, change volume and fade sounds in or out.

Note: The above example was originally written for version 1 of howler.js however version 2 is now out. If you're using version 2 note that you need to change the 'urls' parameter in the example above to 'src'.