Going real simple on HTML5 audio

14 October 2011   0 comments   Web development, Javascript


Powered by Fusion×

DoneCal users are to 80+% Chrome and Firefox users. Both Firefox and Chrome support the HTML <audio> element without any weird plugins and they both support the Ogg Vorbis (.ogg) file format. change log here

So, I used use the rather enterprisey plugin called SoundManager2 which attempts to abstract away all hacks into one single API. It uses a mix of browser sniffing, HTML5 and Flash. Although very promising, it is quite cumbersome. It doesn't work flawlessly despite their hard efforts. Unfortunately, using it also means a 30kb (optimized) Javascript file and a 3kb .swf file (if needed). So, instead of worrying about my very few Internet Explorer users I decided to go really dumb and simple on this.

The solution basically looks like this:

// somewhere.js
var SOUND_URLS = {
  foo: 'path/to/foo.ogg',
  egg: 'path/to/egg.ogg'

// play-sounds.js

/* Call to create and partially download the audo element.
 * You can all this as much as you like. */
function preload_sound(key) {
 var id = 'sound-' + key;
 if (!document.getElementById(id)) {
   if (!SOUND_URLS[key]) {
     throw "Sound for '" + key + "' not defined";
   } else if (SOUND_URLS[key].search(/\.ogg/i) == -1) {
     throw "Sound for '" + key + "' must be .ogg URL";
   var a = document.createElement('audio');
   a.setAttribute('id', id);
   a.setAttribute('src', SOUND_URLS[key]);
 return id;

function play_sound(key) {

// elsewhere.js
   onComplete: function() {
$('#lightbox button').click(function() {

Basically, only Firefox, Chrome and Opera support .ogg but it's a good and open source encoding so I don't mind being a bit of an asshole about it. This little script could be slightly extended with some browser sniffing to work with Safari people but right now it doesn't feel like it's worth the effort.

This make me happy and I feel lean and light. A good feeling!


Your email will never ever be published

Related posts

New feature on Too Cool For Me: Everyone I follow 08 October 2011
Trivial but powerful tips for nosetests 19 November 2011
Related by keywords:
Difference between $.data('foo') and $.attr('data-foo') in jQuery 10 June 2012
RequireJS versus HeadJS 09 January 2011
django-html-validator 20 October 2014
EmailInput HTML5 friendly for Django 02 August 2011
A script tag's type in HTML5 10 May 2011
Welcome to the world: DoneCal.com 22 November 2010
DoneCal.com international visitors 21 January 2011
DoneCal gets a grade A (92) 27 November 2010