使用Modernizr检测html5音频支持

时间:2011-10-23 17:25:10

标签: javascript html5 modernizr

是否可以通过Modernizr检测浏览器是否支持Html5音频?如果是这样,这是怎么做到的?如果不是,有什么工作吗?谷歌解释这一点的资源很少,所以任何帮助都会受到赞赏。

4 个答案:

答案 0 :(得分:8)

是的,通过modernizr.audio。它支持多种音频格式(目前为ogg,mp3,m4a和wmv)。例如:

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

documentation中的更多信息。

答案 1 :(得分:2)

是的,Modernizr检测到音频支持,根据the documentation(这是一个链接),甚至包括一个代码示例(下面复制):

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

答案 2 :(得分:1)

我找到了这段代码,它对我来说很好用:

<!DOCTYPE html>
<html>  
<head>
<title>Play Audio</title>
<script src="script/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="script/modernizr-latest.js" type="text/javascript"></script>
<script type="text/javascript">
var currentFile = "";
function playAudio() {

    var oAudio = document.getElementById('myaudio');
    // See if we already loaded this audio file.
    if ($("#audiofile").val() !== currentFile) {
        oAudio.src = $("#audiofile").val();
        currentFile = $("#audiofile").val();
    }
        var test = $("#myaudio");
        test.src = $("#audiofile").val();
    oAudio.play();   
}

$(function() {
    if (Modernizr.audio) {
        if (Modernizr.audio.wav) {
            $("#audiofile").val("sounds/sample.wav"); 
        }
        if (Modernizr.audio.mp3) {
            $("#audiofile").val("sounds/sample.mp3");
        }
    }
    else {
      $("#HTML5Audio").hide();
      $("#OldSound").html('<embed src="sounds/sample.wav" autostart=false width=1 height=1 id="LegacySound" enablejavascript="true" >');
    }

});
</script>
</head>

<body>
<div style="text-align: center;"> 
 <h1>Click to Play Sound<br /></h1>
<div id="HTML5Audio">
<input id="audiofile" type="text" value="" style="display: none;"/><br />

<button id="play" onclick="playAudio();">
    Play
</button>
</div>
<audio id="myaudio">
    <script>
    function LegacyPlaySound(soundobj) {
      var thissound=document.getElementById(soundobj);
      thissound.Play();
    }
    </script>
    <span id="OldSound"></span>        
    <input type="button" value="Play Sound" onClick="LegacyPlaySound('LegacySound')">
</audio>

只需在文件夹中添加正确名称的音频,然后使用Jquery添加现代化程序文件即可。

答案 3 :(得分:0)

相关问题