1.屬性測試
<!--顯示控制元件-->
<audio src="../images/wind.mp3" id="audioOne" controls="controls"> </audio>
<!--自動播放,顯示控制元件-->
<audio src="../images/wind.mp3" controls="controls" autoplay="autoplay"></audio>
<!--自動迴圈播放,顯示控制元件-->
<audio src="../images/wind.mp3" controls="controls" autoplay="autoplay" loop="loop"></audio>
<!--預載入播放,在頁面載入的時候進行載入檔案,如果指定autoplay了,忽略該屬性-->
<audio src="../images/wind.mp3" controls="controls" preload="metadata"></audio>
2.在 JavaScript 中播放和暫停音訊播放
使用 HTML5 audio 元素入門中所述的 HTML5 audio 元素可向網頁中新增音訊,而無需使用外部控制元件或程式。但是,除非你的網頁只需要一個簡單的音訊播放器,否則你很可能想對載入的音訊檔案及其播放擁有更多的控制。若要將 audio 元素與 JavaScript 結合使用,請定義 audio 標記,該標記具有 “ID” 並且可以選擇省略其他所有內容。如 HTML5 audio 元素入門中所述,你可以顯示或隱藏內建控制元件,或將音訊設定為在頁面載入時自動播放。使用 JavaScript,你仍然可以執行該操作並且還可以執行進一步操作。
在以下示例中,我們在 HTML 中使用簡單的 audio 標記語法。
注意 如果你是在 Intranet 上進行開發並且有 HTML5 的呈現問題,則可以向網頁的 <head> 塊中新增 <meta http-equiv-“X-UA-Compatible” content=”IE=9”/> 以強制 Windows Internet Explorer 9 使用最新標準。如果願意,可以將 Web 開發伺服器配置為傳送帶 IE=9 的元 http-equiv-“X-UA-Compatible” 標頭。
<input type="text" id="audiofile" size="80" value="demo.mp3" />
音訊播放器的所有其他功能可通過 JavaScript 進行控制,如以下指令碼所示。
var currentFile = "";
function playAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
var btn = document.getElementById('play');
var audioURL = document.getElementById('audiofile'); //Skip loading if current file hasn't changed.
if (audioURL.value !== currentFile) {
oAudio.src = audioURL.value;
currentFile = audioURL.value;
} // Tests the paused attribute and set state.
if (oAudio.paused) {
oAudio.play();
btn.textContent = "Pause";
}
else {
oAudio.pause();
btn.textContent = "Play";
}
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
}
在示例的 HTML 部分,為 audio 元素指定 id=”myaudio” 和原始檔 “demo.mp3″。定義 id=”play” 的按鈕和觸發 “playAudio()”JavaScript 函式的 onclick 事件。
在 JavaScript 部分中,使用 document.getElementById 返回 audio 物件。 play 和 pause 方法用於提供播放控制。檢索 button 物件以便可以在“播放”和“暫停”之間切換按鈕標籤,具體情況取決於 audio 物件的 paused 屬性的狀態。 每次呼叫 “playAudio” 函式時都會檢查該狀態。 如果音訊檔案正在播放,則 paused屬性返回 false,並且呼叫 pause 方法來暫停播放。按鈕標籤也設定為“播放”。
如果檔案已暫停,則 paused 屬性返回 true,並且呼叫 play 方法,按鈕標籤更新為“暫停”。第一次載入檔案時,即使尚未顯式呼叫 pause 方法,paused 屬性也返回 true(播放已暫停)。
在 HTML 程式碼中,預設情況下按鈕處於禁用狀態。當頁面載入時,在主體標記中使用 onload 事件呼叫 checkSupport() 函式。如果 audio 元素存在,則啟用按鈕。
3.在 JavaScript 中指定音訊檔案並管理播放
在第一個示例中,通過使用專案的 HTML 部分中的 source 標記來指定音訊原始檔。若要播放多個檔案,則可以將 audio 物件的 src 屬性設定為 JavaScript 中音訊檔案的 URL。
在下一示例中,在 HTML 部分添加了一個文字輸入元素,在其中可以貼上 MPEG-Layer 3 (MP3) 音訊檔案的路徑。
與第一個示例不同,單擊“播放”按鈕可能意味著使用者已更改了音訊檔案或他們已暫停了當前檔案。由於在更改音訊檔案源時呼叫 src 方法會初始化暫停的狀態,因此 “playAudio” 函式必須指示使用者何時想要更改檔案。定義全域性變數 “currentFile”,以便該變數可以跟蹤當前正在播放的檔案的 URL。當用戶單擊“播放”按鈕時,會將 “currentFile” 變數與 “audioURL.value” 指定的文字欄位中的值進行比較。如果這些值不同,則將 src 屬性設定為新檔案 URL,更新 “currentFile” 變數,並呼叫 load 方法。
在本示例中,”currentFile” 變數跟蹤文字欄位的內容,而不是 audio 物件的 src 屬性。原因在於,src 屬性始終是檔案的完全限定路徑,而該檔案可能與文字欄位中的內容不匹配。例如,如果音訊檔案與網頁的原始碼位於相同的目錄中,則可以只指定檔名。如果音訊檔案位於同一域的其他目錄中,則包括路徑,如 “music\demo.mp3″。如果檔案位於其他站點上,則使用完全限定的域名和檔案路徑,如 “http:\\www.contoso.com\music\demo.mp3″。
當音訊檔案正在播放時, currentTime 屬性會跟蹤播放在音訊剪輯中的位置。通過更改 currentTime 的值,你可以快進或快退或重新啟動播放。該示例包括三個用於呼叫 rewindAudio、forwardAudio 和 restartAudio 函式的新按鈕。 rewindAudio 和 forwardAudio 函式將 currentTime 的值減少或增加 30 秒。你可以將增量值更改為更大或更小的跳躍幅度。在 restartAudio 函式中,currentTime 的值設定為零,即表示檔案的開頭。
audio 物件還支援諸如 timeUpdate 事件之類的事件,這些事件用於跟蹤檔案的進度。
// Rewinds the audio file by 30 seconds.
function rewindAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
oAudio.currentTime -= 30.0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
}
// Fast forwards the audio file by 30 seconds.
function forwardAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
oAudio.currentTime += 30.0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
}
// Restart the audio file to the beginning.
function restartAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
oAudio.currentTime = 0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
編寫沒有任何錯誤的程式碼是一件非常困難的事情。本示例包括幾個建議,可能有助於你避免出錯。
注意 此處的示例包括將錯誤傳送到 F12 開發人員工具“控制檯”或“指令碼”選項卡的程式碼。
HTML 語言有一個特點,如果無法識別某個標記,則會將其忽略。在不支援 HTML5 的瀏覽器中,當使用 HTML5 audio 元素時,如果無法識別該元素,則使用標記之間的部分。在本示例中,將顯示訊息 HTML5 Audio is not supported(不支援 HTML5 音訊),但也可以新增任意訊息,使用其他技術,如 Microsoft Silverlight,或允許使用者下載檔案。如果支援 HTML5 音訊,將忽略標記之間的部分。但是,有一個需要注意的問題。對於正常的瀏覽器檢視,audio 標記之間的內容將被忽略,但是如果使用者正在使用螢幕閱讀器檢視網頁,閱讀器也會閱讀標記之間的內容。
在程式碼的 JavaScript 部分,有幾個容易發生錯誤的地方。第一處是在檢查 HTML5 音訊支援性的時候。每個函式通過使用 if (window.HTMLAudioElement)
進行測試,確定是否存在 audio 元素。如果 audio 元素不存在,則不會執行任何程式碼。
在本示例中,如果支援不存在,則會禁用按鈕,也不會呼叫函式。但是,禁用對 JavaScript 函式的訪問對於網頁來說可能不太現實。
如果支援 HTML5 音訊,則可能會發生其他錯誤。Try/catch 語句與可以引發異常的方法結合使用。異常的原因可能是,使用者嘗試播放不存在的檔案、在未載入檔案時後退或無法連線檔案。
使用 Try/catch 語句,這些條件將會失敗,但不會進行提示,但是如果在 Internet Explorer 9 F12 工具中開啟“控制檯”或“指令碼”選項卡,則可以看到這些錯誤。例如,如果未播放或載入任何音訊檔案,則 Fast Forward、Rewind 和 Restart 函式會引發 “InvalidStateError” DOMExceptions。
以下程式碼示例解釋了本主題的所有概念。
<!DOCTYPE html>
<html> <head>
<title>HTML5 Audio Player </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"/> -->
<script type="text/javascript">
// Global variable to track current file name.
var currentFile = "";
function playAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
var btn = document.getElementById('play');
var audioURL = document.getElementById('audiofile'); //Skip loading if current file hasn't changed.
if (audioURL.value !== currentFile) {
oAudio.src = audioURL.value;
currentFile = audioURL.value;
} // Tests the paused attribute and set state.
if (oAudio.paused) {
oAudio.play();
btn.textContent = "Pause";
}
else {
oAudio.pause();
btn.textContent = "Play";
}
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
}
// Rewinds the audio file by 30 seconds. function rewindAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
oAudio.currentTime -= 30.0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
} // Fast forwards the audio file by 30 seconds. function forwardAudio() { // Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
oAudio.currentTime += 30.0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
} // Restart the audio file to the beginning. function restartAudio() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
var oAudio = document.getElementById('myaudio');
oAudio.currentTime = 0;
}
catch (e) {
// Fail silently but show in F12 developer tools console
if(window.console && console.error("Error:" + e));
}
}
} </script>
</head> <body>
<p>
<input type="text" id="audiofile" size="80" value="demo.mp3" />
</p>
<audio id="myaudio">
HTML5 audio not supported
</audio>
<button id="play" onclick="playAudio();">
Play
</button> <button onclick="rewindAudio();">
Rewind
</button>
<button onclick="forwardAudio();">
Fast forward
</button>
<button onclick="restartAudio();">
Restart
</button> </body> </html>