Badass JavaScript

A showcase of awesome JavaScript that pushes the boundaries of what's possible on the web, by @devongovett.

Howler.js: A Cross Browser JavaScript Audio Playback Library Supporting Audio Sprites

January 30th 2013

Howler.js was just released this week and it looks like a nice way to control audio playback from your JavaScript application or game.  It defaults to using the Web Audio API over the HTML5 audio element for performance and control reasons.  For a game, the Web Audio API is really important for precise timing and effects, as compared with the HTML5 audio element which is more suited towards casual audio playback like music or podcast embedding.

Howler.js is a library that makes playing back audio in JavaScript simpler.  It allows you to control when it starts and stops, looping, fading in and out, playback of multiple sounds at the same time, support for multiple codecs and more.  Since browser codec support is not very consistent, you usually have to provide both MP3 and OGG versions if not a WAV fallback as well.  I’ve been involved with implementing codecs themselves in JavaScript to avoid this problem altogether, so I’d be interested to see Howler.js integrate our work there as well, though this is a much simpler approach.

Howler.js allows you to define an array of URLs for different versions of your sound and it will only load the one the current browser supports, either into the Web Audio API or into a normal HTML 5 audio element.  The audio element already allows you to define multiple codecs, but the Web Audio API does not.  For that, you have to implement your own loading of audio files over XHR and detection of what codecs the browser supports is key so you aren’t loading all of them and wasting bandwidth.  Howler.js implements all of this for you, as well as some caching behavior and provides a nice API for it.

Another feature of Howler.js that is pretty interesting is the ability to define “audio sprites”.  You may have heard of image sprites as a way of combining multiple small images into a single one to save HTTP requests.  Audio sprites are a similar idea for short sound effects.  They combine multiple sounds into a single longer one, and only play back the time regions you request.  Howler.js has a nice API for this allowing you to define named time regions within an audio file for each effect and then play back these named regions instead of the whole file.  You can even play back multiple regions simultaneously even though it is technically one file. This is a pretty cool feature that should make sound effects especially for games much easier.

As I’ve said many times, we’re just getting started with audio on the web.  Howler.js looks like a nice way to load and play back audio cross browser.  You can check out the documentation and demos here, and the code on Github.