<Audio> fallback through Javascript

纵饮孤独 提交于 2019-12-24 07:39:41

问题


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.



来源:https://stackoverflow.com/questions/6251638/audio-fallback-through-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!