问题
Is it possible to detect if the browser has Html5 Audio support through Modernizr? If so how is this done? If not are there any work around's? There's few resources on Google explaining this, so any help would be appreciated.
回答1:
Yes, through modernizr.audio. It supports a number of audio formats (currently ogg, mp3, m4a & wmv). Example:
var audio = new Audio();
audio.src = Modernizr.audio.ogg ? 'background.ogg' :
Modernizr.audio.mp3 ? 'background.mp3' :
'background.m4a';
audio.play();
More info in the documentation.
回答2:
Yes, Modernizr detects audio support, according to the documentation (that's a link), which even includes a code sample (copied below):
var audio = new Audio();
audio.src = Modernizr.audio.ogg ? 'background.ogg' :
Modernizr.audio.mp3 ? 'background.mp3' :
'background.m4a';
audio.play();
回答3:
I found this code and it worked fine for me:
<!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>
Just add the audio with the right name in the folder and add the modernizer files with the Jquery stuff and you're done.
回答4:
Yes. http://www.modernizr.com/docs/#installing Half way down.
来源:https://stackoverflow.com/questions/7867807/detecting-html5-audio-support-with-modernizr