欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

使用 JavaScript 控制 Audio 对象

shiping1 的头像

使用 JavaScript 控制 Audio 对象

11(共 15)对本文的评价是有帮助 - 评价此主题

HTML5 中的 audio 对象提供可用于通过 JavaScript 控制播放的方法、属性以及事件。

本部分包括以下主题:

在 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 元素存在,则启用按钮。

在 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 的值,你可以快进或快退或重新启动播放。该示例包括三个用于调用rewindAudioforwardAudio  restartAudio 函数的新按钮。 rewindAudio  forwardAudio 函数将 currentTime 的值减少或增加 30 秒。你可以将增量值更改为更大或更小的跳跃幅度。在 restartAudio 函数中,currentTime 的值设置为零,即表示文件的开头。

你也可以通过调整 playbackRate 属性来更改音频播放速率。 playbackRate 属性是播放速率的加倍器。playbackRate 的值必须为正值,因为负值将导致错误。

audio 对象还支持诸如 timeUpdate 事件之类的事件,这些事件用于跟踪文件的进度。有关如何使用状态和反馈,以及如何添加进度条的详细信息,请参阅使用 Media 事件添加进度条

             // 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));
               }
            }


你也可以通过调整 playbackRate 属性来更改音频播放速率。 playbackRate 属性是播放速率的加倍器。playbackRate 的值必须为正值,因为负值将导致错误。此示例播放一个音频文件,并允许你加快或减慢其播放速率。加速按钮每次向播放速率添加 1,所以视频开始时以正常速率播放,然后每单击一次加速按钮,便会相应增加播放速率的倍数。每单击一次减速按钮,便会使播放速率减慢一倍。这里我们有意将播放速率的跳跃幅度调得很大,目的在于加强演示效果,用户可自行使用较小的增量。

 <!DOCTYPE html>
<html>
  <head>
    <title>Audio playbackRate Example</title>  
</head>
<body>
<div>
  <audio id="audio1" style="width:25%" controls>Canvas not supported</audio>
</div>
<div>
<input type="text" id="audioFile" value="audio.mp3" size="60" />

</div>
  <button id="playbutton" onclick="togglePlay();">Play</button>  
  <button onclick="increaseSpeed();">Increase speed</button>
  <button onclick="decreaseSpeed();">Decrease speed</button><br />
  <div id="rate"></div>

     <script type="text/javascript">
       // Create a couple of global variables to use. 
       var audioElm = document.getElementById("audio1"); // Audio element
       var ratedisplay = document.getElementById("rate"); // Rate display area

       // Hook the ratechange event and display the current playbackRate after each change
       audioElm.addEventListener("ratechange", function () {
         ratedisplay.innerHTML = "Rate: " + audioElm.playbackRate;
       }, false);

       //  Alternates between play and pause based on the value of the paused property
       function togglePlay() {
         if (document.getElementById("audio1")) {

           if (audioElm.paused == true) {
             playAudio(audioElm);    //  if player is paused, then play the file
           } else {
             pauseAudio(audioElm);   //  if player is playing, then pause
           }
         }
       }

       function playAudio(audioElm) {
         document.getElementById("playbutton").innerHTML = "Pause"; // Set button text == Pause
         // Get file from text box and assign it to the source of the audio element 
         audioElm.src = document.getElementById('audioFile').value;
         audioElm.play();
       }

       function pauseAudio(audioElm) {
         document.getElementById("playbutton").innerHTML = "play"; // Set button text == Play
         audioElm.pause();
       }

       // Increment playbackRate by 1 
       function increaseSpeed() {
         audioElm.playbackRate += 1;
       }

       // Cut playback rate in half
       function decreaseSpeed() {
         if (audioElm.playbackRate <= 1) {
           var temp = audioElm.playbackRate;
           audioElm.playbackRate = (temp / 2); 
         } else {
           audioElm.playbackRate -= 1;
         }
       }

     </script>


</body>
</html>


缓存错误

编写没有任何错误的代码是一件非常困难的事情。本示例包括几个建议,可能有助于你避免出错。

注意  此处的示例包括将错误发送到 F12 开发人员工具“控制台”或“脚本”选项卡的代码。有关详细信息,请参阅如何使用 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 ForwardRewind  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>
来自 http://msdn.microsoft.com/zh-cn/library/gg589489%28v=vs.85%29.aspx
普通分类: