在 JavaScript 中播放和暂停音频播放

 利用HTML5 audio 元素,您可以向网页中添加音频,而无需使用外部控件或程序。 但是,除非您的网页只需要一个简单的音频播放器,否则,您很可能想对加载的音频文件和它们的播放拥有更多的控制。若要在 JavaScript 中使用 audio 元素,可以定义一个带有 "ID" 的 audio 标记(可以选择省去其他内容)。 如 HTML5 Audio 元素入门 中所述,您可以显示或隐藏内置控件,或将音频设置为在页面加载时自动播放。 您还可以使用 JavaScript 执行这些操作,甚至执行进一步的操作。

在以下示例中,我们在 HTML 中使用简单的 audio 标记语法。

<input type="text" id="audiofile" size="80" value="demo.mp3" />

 音频播放器的所有其他功能从JavaScript 进行控制,如以下脚本所示。

var currentFile = "";
   function playAudio() {
       // Check for audio elementsupport.
       if (window.HTMLAudioElement){
           try {
               var oAudio =document.getElementById_x_x('myaudio');
               var btn =document.getElementById_x_x('play');
               var audioURL =document.getElementById_x_x('audiofile');
 
               //Skip loading if current file hasn'tchanged.
               if (audioURL.value !== currentFile){
                   oAudio.src = audioURL.value;
                   currentFile = audioURL.value;                      
               }
 
               // Tests the paused attribute and setstate.
               if (oAudio.paused) {
                   oAudio.play();
                   btn.textContent = "Pause";
               }
               else {
                   oAudio.pause();
                   btn.textContent = "Play";
               }
           }
           catch (e) {
               // Fail silently but show in F12developer tools console
                if(window.console&&console.error("Error:" + e));
           }
       }
   }

 在示例的HTML 部分,为 audio 元素指定了 ID "myaudio" 和一个源文件 "demo.mp3"。定义了一个 ID 为 "play" 的按钮和一个触发"playAudio()"JavaScript函数的 onclick 事件。

 在JavaScript 部分,使用 document.getElementById_x_x返回 audio 对象。 play 和 pause 方法用于提供播放控制。 检索 button 对象,从而可以根据 audio 对象的 paused 属性,在“Play”(播放)和“Pause”(暂停)之间切换按钮标签。每次调用 "playAudio" 函数时都会检查该状态。 如果音频文件正在播放,则 paused 属性返回 false,调用pause 方法以暂停播放。 按钮标签也设置为“Play”。

 如果文件已暂停,则paused 属性返回 true,调用play 方法,按钮状态更新为“Pause”。当文件首次加载时,即便未显式调用 pause 方法,paused 属性仍会返回 true(播放已暂停)。

 在HTML 代码中,默认情况下按钮处于禁用状态。 当页面加载时,在主体标记中使用 onload 事件调用 checkSupport() 函数。 如果 audio 元素存在,则启用按钮。

在 JavaScript 中指定音频文件和管理播放

 在第一个示例中,通过使用项目的HTML 部分的 source 标记来指定音频源文件。 若要播放多个文件,您可以从 JavaScript 中将 audio 对象的 src 属性设置为一个音频文件的 URL。

 在下一个示例中,在HTML 部分添加了一个文本输入元素,您可以在其中粘贴 MPEG-Layer 3 (MP3)音频文件的路径。

 与第一个示例不同,单击“Play”按钮可能意味着用户已更改了音频文件或他们已暂停了当前文件。由于在更改音频文件源时调用 src 方法将重置暂停的状态,因此 "playAudio" 函数必须指示用户何时想要更改文件。 定义了全局变量 "currentFile",使之能够跟踪当前播放的文件的URL。当用户单击“Play”按钮时,会将"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 事件。 有关如何使用状态和反馈,以及如何添加进度条的详细信息,请参阅使用 Media 事件添加进度条。

//Rewinds the audio file by 30 seconds.
 function rewindAudio() {
        // Check for audio elementsupport.
       if (window.HTMLAudioElement){
           try {
               var oAudio =document.getElementById_x_x('myaudio');
               oAudio.currentTime -= 30.0;
           }
           catch (e) {
               // Fail silently but show in F12developer tools console
                if(window.console&&console.error("Error:" + e));
           }
       }
   }
 // Fast forwards the audio file by 30seconds.
 function forwardAudio() {
 // Check for audio elementsupport.
       if (window.HTMLAudioElement){
           try {
               var oAudio =document.getElementById_x_x('myaudio');
               oAudio.currentTime += 30.0;
           }
           catch (e) {
               // Fail silently but show in F12developer tools console
                if(window.console&&console.error("Error:" + e));
           }
       }
   }
 // Restart the audio file to thebeginning.
 function restartAudio() {
        // Check for audio elementsupport.
       if (window.HTMLAudioElement){
           try {
               var oAudio =document.getElementById_x_x('myaudio');
               oAudio.currentTime = 0;
           }
           catch (e) {
               // Fail silently but show in F12developer tools console
                if(window.console&&console.error("Error:" + e));
          }
       }

 缓存错误

 很难编写没有错误的代码。本示例包括几个建议,可能有助于您避免出错。

 HTML 语言有一个特点,如果无法识别标记,则将其忽略。 在不支持 HTML5 的浏览器中,当您使用 HTML5 audio 元素时,如果不能识别它,将使用标记之间的部分。 在本示例中,显示了消息HTML5“Audio is notsupported”(不支持音频),但是您可以添加任意消息,使用其他技术,如MicrosoftSilverlight,或允许用户下载文件。如果支持 HTML5 audio,将忽略标记之间的部分。但是,有一个需要注意的问题。 对于正常的浏览器查看,audio 标记之间的内容将被忽略,但是如果用户正在使用屏幕阅读器查看网页,阅读器也会阅读标记之间的内容。

 在代码的JavaScript部分,有几个容易发生错误的地方。第一处是在您检查 HTML5 Audio 支持的时候。 每个函数通过使用 if (window.HTMLAudioElement)进行测试,确定是否存在 audio 元素。 如果 audio 元素不存在,则不会执行任何代码。

 在本示例中,如果支持不存在,则按钮会禁用,也不会调用函数。但是,禁用对 JavaScript 函数的访问对于网页来说可能不太现实。

 如果支持HTML5 Audio,则可能会发生其他错误。Try/catch 语句与可以引发异常的方法结合使用。 异常的原因可能是,用户尝试播放不存在的文件、在未加载文件时后退或无法连接文件。

 

使用 Try/catch 语句,这些条件将会失败,但不会进行提示,但是如果在 Windows Internet Explorer 9F12 开发人员工具中打开“控制台”或“脚本”选项卡,则可以看到这些错误。例如,如果未播放或加载任何音频文件,则 Fast Forward、Rewind 和 Restart 函数会引发 "INVALID_STATE_ERR"DOMExceptions。

以下代码示例解释了本主题的所有概念。

<!DOCTYPE html>
<html>
<head>
   <title>HTML5 Audio Player</title>   
   <!-- Uncomment thefollowing meta tag if you have issues rendering this page on anintranet site. -->   
   <!--  <metahttp-equiv="X-UA-Compatible" content="IE=9"/>--> 
   <script type="text/javascript">
       // Global variable to track currentfile name.
       var currentFile = "";
       function playAudio() {
           // Check for audio elementsupport.
           if (window.HTMLAudioElement){
               try {
                   var oAudio =document.getElementById_x_x('myaudio');
                   var btn =document.getElementById_x_x('play');
                   var audioURL =document.getElementById_x_x('audiofile');
 
                   //Skip loading if current file hasn'tchanged.
                   if(audioURL.value !== currentFile){
                       oAudio.src = audioURL.value;
                       currentFile = audioURL.value;                      
                   }
 
                   // Tests the paused attribute and setstate.
                   if (oAudio.paused) {
                       oAudio.play();
                       btn.textContent = "Pause";
                   }
                   else {
                       oAudio.pause();
                       btn.textContent = "Play";
                   }
               }
               catch (e) {
                   // Fail silently but show in F12developer tools console
                    if(window.console&&console.error("Error:" + e));
               }
           }
       }
            // Rewinds the audio file by 30seconds.
 
       function rewindAudio() {
            // Check for audio elementsupport.
           if (window.HTMLAudioElement){
               try {
                   var oAudio =document.getElementById_x_x('myaudio');
                   oAudio.currentTime -= 30.0;
               }
               catch (e) {
                   // Fail silently but show in F12developer tools console
                    if(window.console&&console.error("Error:" + e));
               }
           }
       }
 
            // Fast forwards the audio file by 30seconds.
 
       function forwardAudio() {
 
            // Check for audio elementsupport.
           if (window.HTMLAudioElement){
               try {
                   var oAudio =document.getElementById_x_x('myaudio');
                   oAudio.currentTime += 30.0;
               }
               catch (e) {
                   // Fail silently but show in F12developer tools console
                    if(window.console&&console.error("Error:" + e));
               }
           }
       }
 
            // Restart the audio file to thebeginning.
 
       function restartAudio() {
            // Check for audio elementsupport.
           if (window.HTMLAudioElement){
               try {
                   var oAudio =document.getElementById_x_x('myaudio');
                   oAudio.currentTime = 0;
               }
               catch (e) {
                   // Fail silently but show in F12developer 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" οnclick="playAudio();">
     Play
   </button>
   
   <button οnclick="rewindAudio();">
     Rewind
   </button>
   <button οnclick="forwardAudio();">
     Fast forward
   </button>
   <button οnclick="restartAudio();">
     Restart
   </button>
 
  </body>
 
</html>