/ audio

howler.js

Browsers have come a long way over the years, and we are now able to achieve amazing results using all of the great new technologies often referred to as HTML5. However, generally speaking, audio still sucks. Thankfully, Google decided to create Web Audio API and make all our lives easier. The problem is that only the latest browsers support this new-fangled browser audio, so what are we to do?

Goldfire Studios has created an open source library for audio in JavaScript called howler.js. I’m currently experimenting with howler and I’ve found it to be quite straightforward to use so far, at least for my current basic needs.

Here’s how it would look to use audio sprites:

var sound = new Howl({
  src: ['sounds/game-sounds.ogg', 'sounds/game-sounds.mp3'],
  sprite: {
    warmSound: [0, 750],
    coldSound: [875, 950],
    winSound: [1930, 2500],
    sameSound: [4518, 850],
    loseSound: [6093, 1700]
  }
});

In the code above, src sets the order of preference for which file to use. If a browser doesn’t support the first file, it will fall back to the second file.

The benefit of using audio sprites for a web app is the same as it would be for image sprites: one file to download as opposed to, in the case above, five.

The numbers after the sprite names are milliseconds: start time and play length. So coldSound above starts at the 875th millisecond and plays for 950 milliseconds.

Note: In the example above, I’m using the 2.0 beta branch. The sprite syntax in the 1.x version of howler is different.