Fallback solution for HTML <audio> and legacy browsers

点点圈 提交于 2019-12-03 21:36:23

You should use both Modernizr as Garret said and jPlayer

Check Garrett's answer on how to check for compatibility. Though I don't see why it would be useful if your only goal is to seamlessly play HTML5 or Flash based on compatibility. jPlayer does it automatically.

You just have to instantiate it:

$("#music").jPlayer({
    ready: function (event) {
        $(this).jPlayer("setMedia", {
            mp3:"music.mp3",
            oga:"music.ogg"
        });
    },
    swfPath: "js",
    supplied: "mp3, oga"
});

The following depends on the interface you want to use. jPlayer has some skins, but you can modify them to your will or just create a whole interface from scratch like I do and use jPlayer methids

You should take a look at the Modernizr script library. This will allow you to perform conditional logic based on what HTML5 features are supported by the browser. For example, you could do something like this:

var audio = new Audio();
audio.src = Modernizr.audio.ogg ? 'background.ogg' :
            Modernizr.audio.mp3 ? 'background.mp3' :
                                  'background.m4a';
audio.play();

Documentation can be found here: http://modernizr.com/docs/#features-html5.

I found another example which I have slightly modified for MP3 to OGG fallback. It uses the canPlayType method:

var audiofile = 'example.mp3';
var audioTag = document.createElement('audio');
if (!(!!(audioTag.canPlayType) && ("no" != audioTag.canPlayType("audio/mpeg"))
      && ("" != audioTag.canPlayType("audio/mpeg")))) {
    audiofile = audiofile.replace('.mp3','.ogg');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!