<Audio> fallback through Javascript

2019-08-04 10:31发布

问题:

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 src="'+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..

回答1:

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.