Skip to content

Instantly share code, notes, and snippets.

@Spaxe
Created April 11, 2012 04:44
Show Gist options
  • Save Spaxe/2356958 to your computer and use it in GitHub Desktop.
Save Spaxe/2356958 to your computer and use it in GitHub Desktop.
Quick and dirty way of selectively loading a playable audio file in HTML5
// Because HTML5 Audio support isn't all that consistent, we need to do something.
// With at least both .ogg and .mp3 formats, they will play on all 5 major
// browsers on the desktop.
// XXX If more ancient support is desired, feel free to add <embed> support. Or Flash.
//
// sources should be a list of audio files of the same sound, but in different formats.
// e.g.: ['effect.ogg', 'effect.mp3', 'effect.wav']
// Depending on the browser capability, it will only add one of them that is playable.
// If no compatible format is found for that browser, a warning will be issued.
// List of Audio MIME Types:
// http://webdesign.about.com/od/sound/a/sound_mime_type.htm
function audio(sources) {
var x = new Audio();
for (var s in sources) {
if (sources.hasOwnProperty(s)) {
var file = sources[s];
if ((file.endswith('.mp3') && x.canPlayType('audio/mpeg')) ||
(file.endswith('.ogg') && x.canPlayType('audio/ogg')) ||
(file.endswith('.mid') && x.canPlayType('audio/mid')) ||
(file.endswith('.m3u') && x.canPlayType('audio/x-mpegurl')) ||
(file.endswith('.ra') && x.canPlayType('audio/x-pn-realaudio'))||
(file.endswith('.wav') &&
(x.canPlayType('audio/wav') || x.canPlayType('audio/x-wav')))
) {
x.src = file;
return x;
}
}
}
// If we got to this point, there wasn't anything we can play
console.warn('None of the audio files in ' + JSON.stringify(sources) + ' are supported.');
return x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment