开发者

<Audio> fallback through Javascript

I want to understand how to implement HTML5 <audio> fallback using Javascript...

i.e. I have a div on my page, to which , I dynamically append <embed> tag when "Play audio" link is clicked currently.. i.e. I currently use

function playSound(audioUrl)
{
var x = document.getElementById("playAudio");
x.innerHTML = '<EMBED sr开发者_如何学运维c="'+audioUrl+'" autostart=true loop=false volume=100 hidden=true>';
} 

I want to have the same thing implemented using the HTML5 <audio> tag, But want to fallback to embed when HTML5 audio tag is not supported. How can I implement the same using JS given that the Audio URL is kind of dynamic ?

My intention is it should work on older as well as newer browsers..like IE6,7,8; FF 3,4; Chrome; Safari 4,5 on MAC, Safari on iPad..


You could use Modernizr to detect audio support.

If you don't want to include that library for a simple thing, this should do it...

var audioSupport = document.createElement('audio').hasOwnProperty('src');

jsFiddle.

So that would be...

function playSound(audioUrl) {
    var audioSupport = document.createElement('audio').hasOwnProperty('src'),
        x = document.getElementById("playAudio");

    if (audioSupport) {
        var audio = document.createElement('audio');
        audio.src = audioUrl;
        x.appendChild(audio);
        audio.play();
    } else {
        // Or you could use proper DOM methods...
        x.innerHTML = '<EMBED src="' + audioUrl + '" autostart=true loop=false volume=100 hidden=true>';
    }
}

jsFiddle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜