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));
}
}
 
4.缓存错误

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

注意  此处的示例包括将错误发送到 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>

<audio>使用2的更多相关文章

  1. html5 audio总结

    前言 html5中对音频,视频播放原生支持.最近做了一个音乐播放器,得益于快过年了,才能抽出一点时间来总结一下.总的来说,html5对audio的支持非常强大, 难怪flash要死.浏览器上装播放插件 ...

  2. 《HTML5》 Audio/Video全解

    一.标签解读 <audio> 标签属性 <audio id="media" src="http://www.abc.com/test.mp3" ...

  3. video/audio在ios/android上播放兼容

    1.audio自动播放 <audio src='xxx.mp3' autoplay></audio> 上面是audio标签autoplay属性是自动播放,但是在安卓部分浏览器和 ...

  4. audio 基本功能实现(audio停止播放,audio如何静音,audio音量控制等)

    audio最简单原始的播放.暂停.停止.静音.音量大小控制的功能,注意某些浏览器会有权限无法自动播放噢(video也会如此) <!doctype html> <html> &l ...

  5. h5自定义audio(问题及解决)

    h5活动需要插入音频,但又需要自定义样式,于是自己写咯 html <!-- cur表示当前时间 max表示总时长 input表示进度条 --> <span class='cur'&g ...

  6. Your app declares support for audio in the UIBackgroundModes key in your Info.plist 错误

    提交AppStore时候被拒绝 拒绝原因:Your app declares support for audio in the UIBackgroundModes key in your Info.p ...

  7. HTML5的Audio标签打造WEB音频播放器

    目前,WEB页面上没有标准的方式来播放音频文件,大多数的音频文件是使用插件来播放,而众多浏览器都使用了不同的插件.而HTML5的到来,给我们提供了一个标准的方式来播放WEB中的音频文件,用户不再为浏览 ...

  8. 微信的audio无法自动播放的问题

    一.问题 最近做了一个html5的项目,里面涉及到音乐播放,项目要求音乐进入页面就自动播放,于是我就想到了html5的audio标签,将mp3引入进去. 1.在audio标签里引入了autoplay属 ...

  9. HTML5 audio与video标签实现视频播放,音频播放

    随着互联网的飞速发展以及HTML5的应用,越来越多的项目中用到video,audio当常用标签. <audio> 标签属性 <audio src="song.mp3&quo ...

  10. android audio无法自动播放

    audio无法在android4.4+和ios6以上的版本自动播放,因为他们出于安全考虑,做了限制.必须用户自己手工点击才能播放,程序是控制不了播放的. 整死我了,整整搞了2天,查不出所以然,原来就这 ...

随机推荐

  1. OMXCodec与OMX事件处理流程

    学习了解Mutilmedia Framework有一段时间了,今天闲下来稍微整理整理.OMXCodec.cpp类属于libstagefright,在整个MM PF 相当OMX的适配层,供awesome ...

  2. CLR via C# - Char_String

    .NET中Char表示为16为的Unicode值,Char提供两个public const字段MinValue('\0',写成'\u0000'也是一样的)和MaxValue('\uffff'). Ch ...

  3. PHP学习笔记三十四【记录日志】

    <?php function my_error2($errno,$errmes) { echo "错误号:".$errno; //默认时区是格林威治相差八个时区 //设置 1 ...

  4. C#总结(2)

    有输出,当然有输入.这样才会有人机交互. using System; using System.Collections.Generic; using System.Linq; using System ...

  5. (原+转)Ubuntu下安装understand及在启动器中增加快捷方式

    参考网址: http://www.xuebuyuan.com/1353431.html http://www.2cto.com/os/201309/242543.html http://my.osch ...

  6. JavaScript this 局部变量全局变量 作用域 作用域链 闭包

    从阮老师博客的一道测试题说起: 代码段一: var name = "The Window"; var object = { name : "My Object" ...

  7. js经典代码技巧学习之一:使用三元运算符处理javascript兼容

    window.Event = { add: function() { //使用条件表达式检测标准方法是否存在 return document.addEventListener ? function(a ...

  8. dede调用指定栏目的标签

    {dede:type typeid='1'} <a href="[field:typelink /]">[field:typename /]</a> {/d ...

  9. Mysql MEMORY 引擎

    CREATE TABLE `m` ( `) unsigned NOT NULL AUTO_INCREMENT, `name` ) NOT NULL, `ctime` ) NOT NULL, `ltim ...

  10. iOS Layer CABasicAnimation

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/c ...