Skip to content

Instantly share code, notes, and snippets.

@NielsLeenheer
Forked from westonruter/canPlayAudioMP3.js
Created April 15, 2010 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NielsLeenheer/367545 to your computer and use it in GitHub Desktop.
Save NielsLeenheer/367545 to your computer and use it in GitHub Desktop.
/**
* Detect if the browser can play MP3 audio using native HTML5 Audio.
* Invokes the callack function with first parameter is the boolean success
* value; if that value is false, a second error parameter is passed. This error
* is either HTMLMediaError or some other DOMException or Error object.
* Note the callback is likely to be invoked asynchronously!
* @param {function(boolean, Object|undefined)} callback
*/
function canPlayAudioMP3(callback){
try {
var audio = new Audio();
//Shortcut which doesn't work in Chrome (always returns ""); pass through
// if "maybe" to do asynchronous check by loading MP3 data: URI
if(audio.canPlayType('audio/mpeg') == "probably")
callback(true);
//If this event fires, then MP3s can be played
audio.addEventListener('canplaythrough', function(e){
callback(true);
}, false);
//If this is fired, then client can't play MP3s
audio.addEventListener('error', function(e){
callback(false, this.error)
}, false);
//Smallest base64-encoded MP3 I could come up with (<0.000001 seconds long)
audio.src = "data:audio/mpeg;base64,/+MYxAAAAANIAAAAAExBTUUzLjk4LjIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
audio.load();
}
catch(e){
callback(false, e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment