Simple HTML5 Audio Sprite

A simple example to illustrate the audio sprite solution for overcoming the HTML5 audio limitations in mobile Safari.

by jonnyc

HTML

<audio id="audio">
    <source src="http://dl.dropbox.com/u/1538714/article_resources/cat.m4a" type="audio/mpeg" />
    <source src="http://dl.dropbox.com/u/1538714/article_resources/cat.ogg" type="audio/ogg" />
</audio>
<button onclick="playSprite('meow1');">Play Meow 1 Sprite</button>
<button onclick="playSprite('meow2');">Play Meow 2 Sprite</button>
<button onclick="playSprite('whine');">Play Whine Sprite</button>
<button onclick="playSprite('purr');">Play Purr Sprite</button>

JavaScript

var audioSprite = document.getElementById('audio');

// sprite data
var spriteData = {
    meow1: {
        start: 0,
        length: 1.1
    },
    meow2: {
        start: 1.3,
        length: 1.1
    },
    whine: {
        start: 2.7,
        length: 0.8
    },
    purr: {
        start: 5,
        length: 5
    }
};

// current sprite being played
var currentSprite = {};

// time update handler to ensure we stop when a sprite is complete
var onTimeUpdate = function() {
    if (this.currentTime >= currentSprite.start + currentSprite.length) {
        this.pause();
    }
};
audioSprite.addEventListener('timeupdate', onTimeUpdate, false);

// in mobile Safari, the first time this is called will load the audio. Ideally, we'd load the audio file completely before doing this.
var playSprite = function(id) {
    if (spriteData[id] && spriteData[id].length) {
        currentSprite = spriteData[id];
        audioSprite.currentTime = currentSprite.start;
        audioSprite.play();
    }
};