HTML5 supports playing audio and video files directly in the browser, without using plug-ins such as Abode Flash.
1. Use the video element
You can use the video element to embed video content in the web page.
The basic usage is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用video元素</title> </head> <body> <video width="360" height="240" src="timessquare.webm" autoplay controls preload="none" muted> Video cannot be displayed </video> </body> </html>
The display effect of this example is as follows:
If the browser does not support the video element or cannot play the video, then the backup content (the content within the opening and closing tags) will be displayed instead. In this example, a simple text message is displayed, but a common technique is to provide video playback using HTML5 technology (such as Flash) to support older browsers. The
video element has many attributes, and the following table lists them:
1.1 Preloading the video
The preload attribute tells the browser whether it should actively download the video after it has loaded the web page containing the video element. . Preloading the video reduces the initial delay when the user plays it, but wastes network bandwidth if the user does not watch the video. The following table describes the allowed values for this property.
When deciding whether to preload a video, you should weigh the likelihood that the user will want to watch the video versus the bandwidth required to automatically load the video content. Autoloading videos will result in a smoother user experience, but it can significantly increase operating costs, which are wasted if users leave the page without watching the video.
The metadata value of this attribute can be used to establish a moderate balance between none and auto values. The problem with the none value is that the video content will appear as a blank space on the screen. The metadata value will allow the browser to obtain enough information to show the user the first frame of the video without having to download the entire content.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>将none和metadata值用于preload属性</title> </head> <body> <video width="360" height="240" src="timessquare.webm" controls preload="none" muted> Video cannot be displayed </video> <video width="360" height="240" src="timessquare.webm" controls preload="metadata" muted> Video cannot be displayed </video> </body> </html>
This example
PS: The metadata value provides a beautiful preview screen to the user, but some caution is required. When testing this property with a network analysis tool, it was discovered that some browsers would actually pre-download the entire video despite only requesting metadata. To be fair, browsers are free to choose whether to ignore the preference expressed by the preload attribute. However, if you need to limit bandwidth consumption, the poster attribute may be better.
shows the use of none and metadata values in the same document. The display effect is as follows. You can see how these values affect the preview screen displayed to the user.
1.2 Display placeholder image
You can use the poster attribute to present a placeholder image to the user. This image will be displayed in place of the video until the user starts playback.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用poster属性来指定占位图像</title> </head> <body> <video width="360" height="240" src="timessquare.webm" controls preload="none" poster="poster.png"> Video cannot be displayed </video> <img src="poster.png" / alt="【HTML5】Use multimedia" > </body> </html>
Here I took a screenshot of the first frame of the video file and then superimposed the word Poster on top of it. This image includes video controls to remind the user that this poster represents a video clip. An img element is also added to this example to demonstrate that the video element will display the poster image unchanged.
1.3 Set video size
If the width and height attributes are omitted, the browser will display a small placeholder element and display it when metadata is available (that is, when the user starts playing, or the preload attribute is set When it is metadata) adjust it to the original size of the video. This can create a juddery feeling as the page layout needs to adjust to accommodate the video.
If you specify the width and height attributes, the browser will maintain the video's aspect ratio (don't worry about the video stretching in either direction).
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>应用width和height属性</title> <style> video {background-color: gray;border: medium double green;} </style> </head> <body> <video width="600" height="240" src="timessquare.webm" controls preload="auto"> Video cannot be displayed </video> </body> </html>
The ratio between the width attribute and the height attribute set in this example is unbalanced. A style is also applied to the video element to highlight that in order to maintain the length, width and height of the video, the browser will only use part of the space assigned to the element.
1.4 Specifying video source (and format)
The easiest way to specify a video is to use the src attribute and provide the URL of the desired video file.
You can see that in the previous example, the file timessquare.webm was specified with the src attribute. This is a file encoded in WebM format. At present, no video format is universally supported. If you want to promote videos to a variety of HTML5 users, you must be prepared to encode videos in multiple formats.
The unfortunate truth is that no single format works in all major browsers. Therefore, the video must be encoded in multiple formats until one format emerges. Multiple formats can be specified using the source element.
下面例子展示了如何使用 source元素来向浏览器提供备选视频格式。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用source元素</title> </head> <body> <video width="360" height="240" controls preload="auto"> <source src="timessquare.webm" /> <source src="timessquare.ogv" /> <source src="timessquare.mp4" /> Video cannot be displayed </video> </body> </html>
浏览器会沿着列表顺序寻找它能够播放的视频文件。这可能会引发多个服务器请求以获得每个文件的额外信息。浏览器判断它是否能播放某个视频的依据之一是服务器返回的MIME类型。可以通过给source元素应用type属性来提示用户,方法是在其中指定文件的MIME类型。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>在source元素上应用type属性</title> </head> <body> <video width="360" height="240" controls preload="auto"> <source src="timessquare.webm" type="video/webm" /> <source src="timessquare.ogv" type="video/ogg" /> <source src="timessquare.mp4" type="video/mp4" /> Video cannot be displayed </video> </body> </html>
2. 使用 audio 元素
audio 元素允许在HTML文档里嵌入音频内容。
可以看到audio和video元素有许多共同点。下面的例子展示了audio元素的用法。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用audio元素</title> </head> <body> <audio controls src="P!NK - Just Give Me a Reason.mp3" autoplay> Audio content cannot be played </audio> </body> </html>
也可以使用source元素来提供多种格式。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用audio元素</title> </head> <body> <audio controls autoplay> <source src="P!NK - Just Give Me a Reason.ogg" /> <source src="P!NK - Just Give Me a Reason.mp3" /> <source src="P!NK - Just Give Me a Reason.wav" /> Audio content cannot be played </audio> </body> </html>
这两个例子都使用了controls属性,这样浏览器就会对用户显示默认的播放控件。它们在不同的浏览器中外观各异,下面是在火狐浏览器中的显示效果:
3. 通过 DOM 操作嵌入式媒体
audio 和 video 元素有着很大的相似性,所以HTMLMediaElement对象在DOM里为它们统一定义了核心功能。audio元素在DOM里由HTMLAudioElement对象所代表,但此对象没有定义不同于HTMLMediaElement的额外功能。video元素由HTMLVideoElement对象所代表,而它定义了一些额外的属性。
PS: audio和video元素的相似度是如此之高,以至于它们唯一区别仅仅是在屏幕上占据的空间大小。audio元素不会占用一大块屏幕空间来显示视频图像。事实上,甚至可以用audio元素来播放视频文件(当然,这么做只能听得到配乐),也可以用video元素来播放音频文件(不过视频显示区域会保持空白)。这看起来很奇怪,但其实是可行的。
3.1 获得媒体信息
HTMLMediaElement 对象定义了许多成员,可以用它们来获取和修改元素及其关联媒体的信息。
对象定义了下表中展示的额外属性:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>获取媒体元素的基本信息</title> <style> table {border: thin solid orange;border-collapse: collapse;} th,td {padding: 2px 4px;} body > * {float: left;margin: 2px;} </style> </head> <body> <video id="media" width="360" height="240" controls preload="metadata"> <source src="timessquare.webm" type="video/webm" /> <source src="timessquare.ogv" type="video/ogg" /> <source src="timessquare.mp4" type="video/mp4" /> Video cannot be displayed </video> <table id="info" border="1"> <tr><th>Property</th><th>Value</th></tr> </table> <script type="application/javascript"> var mediaElem = document.getElementById("media"); var tableElem = document.getElementById("info"); var propertyNames = ["autoplay","currentSrc","controls","loop","muted","preload","src","volume"]; for(var i=0;i<propertyNames.length;i++){ tableElem.innerHTML += "<tr><td>"+propertyNames[i]+"</td><td>"+mediaElem[propertyNames[i]]+"</td></tr>"; } </script> </body> </html>
此例的脚本在一张表格中显示了许多属性的值,位置就在video元素的旁边,展示了如何使用一些HTMLMediaElement属性来获取媒体元素的基本信息。
3.2 评估回放能力
canPlayType 方法用来了解浏览器是否能够播放特定的媒体格式。这个方法会返回下表里列出的其中一个值:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用canPlayType方法</title> <style> table {border: thin solid orange;border-collapse: collapse;} th,td {padding: 2px 4px;} body > * {float: left;margin: 2px;} </style> </head> <body> <video id="media" width="360" height="240" controls preload="metadata"> Video cannot be displayed </video> <table id="info" border="1"> <tr><th>Property</th><th>Value</th></tr> </table> <script type="application/javascript"> var mediaElem = document.getElementById("media"); var tableElem = document.getElementById("info"); var mediaFiles = ["timessquare.webm","timessquare.ogv","timessquare.mp4"]; var mediaTypes = ["video/webm","video/ogv","video/mp4"]; for(var i=0;i<mediaTypes.length;i++){ var playable = mediaElem.canPlayType(mediaTypes[i]); if(!playable){ playable = "no"; } tableElem.innerHTML += "<tr><td>" + mediaTypes[i] + "</td><td>"+ playable +"</td></tr>"; if(playable == "probably"){ mediaElem.src = mediaFiles; } } </script> </body> </html>
此例的脚本中,用canPlayType 方法评估了一组媒体类型。如果收到一个 probably 答复,就会设置video元素的src属性值。通过这种方式,此例在一张表格里记录了三种媒体类型的答复。
用这种方式选择媒体时需要多加小心,因为浏览器评估自身格式播放能力的方法各不相同。
很难评论浏览器在答复中所表现出的不一致性。有太多因素使它们无法给出明确的答案,但它们在评估支持时使用不同方式这一点意味着应当非常谨慎的使用canPlayType方法。
3.3 控制媒体回放
HTMLMediaElement 对象定义了许多成员,它们能够控制回放和获得回放信息。这些属性和方法如下表所示:
下面的例子展示了如何使用表格中的属性来获取回放信息:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用HTMLMediaElement属性获取媒体回放详情</title> <style> table {border: thin solid black;border-collapse: collapse;} th,td {padding: 2px 4px;} body > * {float: left;margin: 2px;} div {clear: both;} </style> </head> <body> <video id="media" width="360" height="240" controls preload="metadata"> <source src="timessquare.webm" type="video/webm" /> <source src="timessquare.ogv" type="video/ogg" /> <source src="timessquare.mp4" type="video/mp4" /> Video cannot be displayed </video> <table id="info" border="1"> <tr><th>Property</th><th>Value</th></tr> </table> <div> <button id="pressme">Press Me</button> </div> <script type="application/javascript"> var mediaElem = document.getElementById("media"); var tableElem = document.getElementById("info"); document.getElementById("pressme").onclick = function(){ var propertyNames = ["currentTime","duration","paused","ended"]; tableElem.innerHTML = ""; for(var i=0;i<propertyNames.length;i++){ tableElem.innerHTML += "<tr><td>"+propertyNames[i]+"</td><td>"+mediaElem[propertyNames[i]]+"</td></tr>"; } } </script> </body> </html>
此例包含一个button元素,当它被按下后会使表格显示出currentTime、duration、paused 和 ended 属性的当前值。
可以使用回放方法代替默认的媒体空间,演示例子如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>替换默认的媒体控件</title> </head> <body> <video id="media" width="360" height="240" preload="metadata"> <source src="timessquare.webm" type="video/webm" /> <source src="timessquare.ogv" type="video/ogg" /> <source src="timessquare.mp4" type="video/mp4" /> Video cannot be displayed </video> <div> <button>Play</button> <button>Pause</button> </div> <script type="application/javascript"> var mediaElem = document.getElementById("media"); var buttons = document.getElementsByTagName("button"); for (var i=0;i<buttons.length;i++){ buttons[i].onclick = handleButtonPress; } function handleButtonPress(e){ switch(e.target.innerHTML){ case 'Play': mediaElem.play(); break; case 'Pause': mediaElem.pause(); } } </script> </body> </html>
此例中,省略了video元素的controls属性,并用点击button元素触发的play和pause方法来启动和停止媒体回放。