HTML5 Audio and Modernizr

May 14, 2011

Previously, I was generating HTML5 audio elements into my source and then getting a handle to them by id. It turns out there's a simpler way - you can create audio instances directly in JavaScript by using new Audio('path').

That does, however, leave the problem of formats. Some browsers support ogg, others support mp3 and some only support .wav.

Here's a JavaScript function that will take a path to an audio file, for example /site_media/sounds/snare. It will then work out what file types this browser supports (using Modernizr) and then add the appropriate extension, returning an Audio instance.

function createAudio(pPath){
  if (pPath){
   var lExtension = '.wav';
    if (Modernizr.audio && Modernizr.audio.ogg){
      lExtension = '.ogg';
    } 
    else if (Modernizr.audio && Modernizr.audio.mp3){
      lExtension = '.mp3';
    }

    var lAudio = new Audio(pPath + lExtension);
    return lAudio;
  }
  return null;
}

We can now call play() and pause() on this sound from JavaScript.

References

Tags: html5 audio modernizr