通過使用 audio 元素或對象支援多個音頻格式,你可以将更多的聽衆從多個浏覽器吸引到你的網頁上。
使用源元素指定多個音頻格式
在将 HTML5 audio 元素添加到代碼時,可以指定一條在浏覽器不支援 audio 标記時顯示的錯誤消息
如果你使用的浏覽器根本不支援音頻,這将很有效。但是,如果支援 audio 元素,但不支援檔案格式,則不會顯示你指定的錯誤消息。由于在支援 HTML5 的所有浏覽器中僅存在幾種支援的格式,是以要赢得最大範圍的閱聽人,則可以使用 source 元素指定要嘗試的多種檔案格式。下面的示例示範了三種格式。
<!doctype html>
<head>
<title>
Multiple format audio example
</title>
<!-- Uncomment the following meta tag if you have issues rendering this page on an intranet site. -->
<!-- <meta http-equiv="X-UA-Compatible" content="IE=9"/> -->
</head>
<body>
<h1>
Using source to support multiple audio formats
</h1>
<!-- The browser will automatically choose the format it supports. -->
<audio controls="true">
<source src="demo.mp3" type="audio/mp3">
<source src="demo.ogg" type="audio/ogg">
<source src="demo.aac" type="audio/mp4">
<!-- If no support at all. -->
HTML5 audio not supported
</audio>
</body>
</html>
在本示例中,你指定了三種格式。浏覽器将自動選擇它支援的格式,如果根本就不支援音頻,則它将調用錯誤消息。
利用 JavaScript 确定音頻檔案格式支援
利用 JavaScript 查明使用的格式比源元素的簡單故障轉移模型要 複雜一些。但是,在确定可用的支援後,便可以為餘下的會話進行格式假設。
audio 對象将提供 canPlayType 方法以便預測試浏覽器 的檔案格式功能。 canPlayType 方法帶有一個音頻 mime 類型、編解碼器(可選)參數,并且傳回三個字元串之一:empty、maybe 或 probably。
下面的代碼示例将測試三類音頻檔案格式(MPEG-Layer 3 (MP3)、ogg 和 aac)。
<!doctype html>
<head>
<title>Using multiple file formats in JavaScript</title>
<!-- Uncomment the following meta tag if you have issues rendering this page on an intranet site. -->
<!-- <meta http-equiv="X-UA-Compatible" content="IE=edge"/> -->
<script type= "text/javascript">
function checkAudioCompat() {
var myAudio = document.createElement('audio');
var msg = document.getElementById("display");
msg.innerHTML = "";
if (myAudio.canPlayType) {
// CanPlayType returns maybe, probably, or an empty string.
var playMsg = myAudio.canPlayType('audio/mpeg');
if ( "" != playMsg) {
msg.innerHTML += "mp3 is " + playMsg + " supported<br/>";
}
playMsg = myAudio.canPlayType('audio/ogg; codecs="vorbis"');
if ( "" != playMsg){
msg.innerHTML += "ogg is " + playMsg + " supported<br/>";
}
playMsg = myAudio.canPlayType('audio/mp4; codecs="mp4a.40.5"');
if ( "" != playMsg){
msg.innerHTML += "aac is "+playMsg+" supported<br/>";
}
}
else {
msg.innerHTML += "no audio support";
}
}
</script>
</head>
<body>
<button onclick="checkAudioCompat();">
Test for audio format type
</button>
<div id="display"> </div>
</body>
</html>
在使用 Internet Explorer 9 中的新元素和功能時,最好是始終測試實作的 功能。為了檢查支援,功能最初會通過使用
document.createElement()
變量建立音頻對象。如果音頻對象成功建立,則語句 “if (myAudio.canPlayType)” 傳回 true,并且繼續執行以測試特定的檔案類型。
var playMsg = myAudio.canPlayType('audio/mpeg');
if ( "" != playMsg) {
msg.innerHTML += "mp3 is " + playMsg + " supported<br/>";
}