From:https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video

Using HTML5 audio and video

HTML5 introduces built-in media support via the <audio> and <video> elements, offering the ability to easily embed media into HTML documents.

Embedding mediaEdit

Embedding media in your HTML document is trivial:

<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" controls>
Your browser does not support the <code>video</code> element.
</video>

This example plays a sample video, with playback controls, from the Theora web site.

Here is an example for embedding audio into your HTML document

<audio src="/test/audio.ogg">
<p>Your browser does not support the <code>audio</code> element.</p>
</audio>
 

The src attribute can be a URL of the audio file or the path to the file on the local system.

<audio src="audio.ogg" controls autoplay loop>
<p>Your browser does not support the <code>audio</code> element </p>
</audio>
 

This code example uses attributes of the <audio> element:

  • controls : Displays the standard HTML5 controls for the audio on the web page.
  • autoplay : Makes the audio play automatically.
  • loop : Make the audio repeat (loop) automatically.
<audio src="audio.mp3" preload="auto" controls></audio>
 

The preload attribute is used in the audio element for buffering large files. It can take one of 3 values:

  • "none" does not buffer the file
  • "auto" buffers the media file
  • "metadata" buffers only the metadata for the file

Multiple source files can be specified using the <source> element in order to provide video or audio encoded in different formats for different browsers. For instance:

<video controls>
<source src="SampleVideo.ogv" type="video/ogv">
<source src="SampleVideo.mp4" type="video/mp4">
Your browser does not support the <code>video</code> element.
</video>

This plays the Ogg video file in browsers supporting the Ogg format. If the browser doesn't support Ogg video, the browser uses the MPEG-4 file. See also the list of media formats supported by the audio and video elements in different browsers.

You may also specify which codecs the media file requires; this allows the browser to make even more intelligent decisions:

<video controls>
<source src="SampleVideo.ogv" type="video/ogv; codecs=dirac, speex">
Your browser does not support the <code>video</code> element.
</video>

Here, we specify that the video uses the Dirac and Speex codecs. If the browser supports Ogg video, but not the specified codecs, the video will not load.

If the type attribute isn't specified, the media's type is retrieved from the server and checked to see if the browser can handle it; if it can't be rendered, the next source is checked. If none of the specified source elements can be used, an error event is dispatched to the video element. If the type attribute is specified, it's compared against the types the browser can play, and if it's not recognized, the server doesn't even get queried; instead, the next source is checked at once.

See Media events for a complete list of events associated with media playback. For details on media formats supported by different browsers, see Media formats supported by the audio and video elements.

Controlling media playbackEdit

Once you've embedded media into your HTML document using the new elements, you can programmatically control them from JavaScript code. For example, to start (or restart) playback, you can do this:

var v = document.getElementsByTagName("video")[0];
v.play();

The first line fetches the first video element in the document, and the second calls the element's play() method, as defined in the nsIDOMHTMLMediaElement interface that is used to implement the media elements.

Controlling an HTML5 audio player to play, pause, increase and decrease volume using some Javascript is straightforward.

<audio id="demo" src="audio.mp3"></audio>
<div>
<button onclick="document.getElementById('demo').play()">Play the Audio</button>
<button onclick="document.getElementById('demo').pause()">Pause the Audio</button>
<button onclick="document.getElementById('demo').volume+=0.1">Increase Volume</button>
<button onclick="document.getElementById('demo').volume-=0.1">Decrease Volume</button>
</div>

Stopping the download of mediaEdit

While stopping the playback of media is as easy as calling the element's pause() method, the browser keeps downloading the media until the media element is disposed of through garbage collection.

Here's a trick that stops the download at once:

var mediaElement = document.getElementById("myMediaElementID");
mediaElement.pause();
mediaElement.src='';
//or
mediaElement.removeAttribute("src");

By removing the media element's src attribute (or setting it to an empty string—it may depend on the browser), you destroy the element's internal decoder, which stops the network download. The spec is quite unclear on the removeAttribute() scenario and setting a <video> 'src' attribute to an empty string can cause an unwanted request (Mozilla Firefox 22).

Seeking through mediaEdit

Media elements provide support for moving the current playback position to specific points in the media's content. This is done by setting the value of the currentTime property on the element; see HTMLMediaElement for further details on the element's properties. Simply set the value to the time, in seconds, at which you want playback to continue.

You can use the element's seekable property to determine the ranges of the media that are currently available for seeking to. This returns a TimeRanges object listing the ranges of times that you can seek to.

var mediaElement = document.getElementById('mediaElementID');
mediaElement.seekable.start(0); // Returns the starting time (in seconds)
mediaElement.seekable.end(0); // Returns the ending time (in seconds)
mediaElement.currentTime = 122; // Seek to 122 seconds
mediaElement.played.end(0); // Returns the number of seconds the browser has played

Specifying playback rangeEdit

When specifying the URI of media for an <audio> or <video> element, you can optionally include additional information to specify the portion of the media to play. To do this, append a hash mark ("#") followed by the media fragment description.

A time range is specified using the syntax:

#t=[starttime][,endtime]

The time can be specified as a number of seconds (as a floating-point value) or as an hours/minutes/seconds time separated with colons (such as 2:05:01 for 2 hours, 5 minutes, and 1 second).

A few examples:

http://example.com/video.ogv#t=10,20
Specifies that the video should play the range 10 seconds through 20 seconds.
http://example.com/video.ogv#t=,10.5
Specifies that the video should play from the beginning through 10.5 seconds.
http://example.com/video.ogv#t=,02:00:00
Specifies that the video should play from the beginning through two hours.
http://example.com/video.ogv#t=60
Specifies that the video should start playing at 60 seconds and play through the end of the video.

The playback range portion of the media element URI specification was added to Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6). At this time, this is the only part of the Media Fragments URI specification implemented by Gecko, and it can only be used when specifying the source for media elements, and not in the address bar.

Fallback optionsEdit

HTML included between, for example, the opening and closing tags of media elements is processed by browsers that don't support HTML5 media. You can take advantage of this fact to provide alternative fallback media for those browsers.

This section provides two possible fallback options for video. In each case, if the browser supports HTML5 video, that is used; otherwise, the fallback option is used.

Using Flash

You can use Flash to play a Flash format movie if the <video> element isn't supported:

<video src="video.ogv" controls>
<object data="flvplayer.swf" type="application/x-shockwave-flash">
<param value="flvplayer.swf" name="movie"/>
</object>
</video>

Note that you shouldn't include classid in the object tag in order to be compatible with browsers other than Internet Explorer.

Playing Ogg videos using a Java applet

There's a Java applet called Cortado that you can use as a fallback to play Ogg videos in browsers that have Java support but don't support HTML5 video:

<video src="my_ogg_video.ogv" controls width="320" height="240">
<object type="application/x-java-applet" width="320" height="240">
<param name="archive" value="cortado.jar">
<param name="code" value="com.fluendo.player.Cortado.class">
<param name="url" value="my_ogg_video.ogv">
<p>You need to install Java to play this file.</p>
</object>
</video>

If you do not create an alternate child element of the cortado object element, such as the <p> element above, FireFox 3.5 installations that handle the video natively but do not have Java installed will incorrectly inform the user that they need to install a plugin to view content on the page.

Error handling

(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)

Starting in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1), error handling has been revised to match the latest version of the HTML5 specification. Instead of the error event being dispatched to the media element itself, it now gets delivered to the child <source> elements corresponding to the sources resulting in the error.

This lets you detect which sources failed to load, which may be useful. Consider this HTML:

<video>
<source id="mp4_src"
src="video.mp4"
type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</source>
<source id="3gp_src"
src="video.3gp"
type='video/3gpp; codecs="mp4v.20.8, samr"'>
</source>
<source id="ogg_src"
src="video.ogv"
type='video/ogv; codecs="theora, vorbis"'>
</source>
</video>

Since Firefox doesn't support MP4 and 3GP due to their patent-encumbered nature, the <source> elements with the IDs "mp4_src" and "3gp_src" will receive error events before the Ogg resource is loaded. The sources are tried in the order in which they appear, and once one loads successfully, the remaining sources aren't tried at all.

Detecting when no sources have loaded

To detect that all child <source> elements have failed to load, check the value of the media element's networkState attribute. If this is HTMLMediaElement.NETWORK_NO_SOURCE, you know that all the sources failed to load.

If at that point you add another source by inserting a new <source> element as a child of the media element, Gecko attempts to load the specified resource.

Showing fallback content when no source could be decoded

Another way to show the fallback content of a video when none of the sources could be decoded in the current browser is to add an error handler on the last source element. Then you can replace the video with its fallback content:

<video controls>
<source src="dynamicsearch.mp4" type="video/mp4"></source>
<a href="dynamicsearch.mp4">
<img src="dynamicsearch.jpg" alt="Dynamic app search in Firefox OS">
</a>
<p>Click image to play a video demo of dynamic app search</p>
</video>
var v = document.querySelector('video'),
sources = v.querySelectorAll('source'),
lastsource = sources[sources.length-1];
lastsource.addEventListener('error', function(ev) {
var d = document.createElement('div');
d.innerHTML = v.innerHTML;
v.parentNode.replaceChild(d, v);
}, false);

See alsoEdit

Using HTML5 audio and video的更多相关文章

  1. HTML5 Audio and Video 的新属性简介

    前言:HTML5 中 Audio and Video的使用方法比较简单,但就是比较复杂,方法属性多.如果不常用的几乎难以记住,甚至有些人难以区分不同属性和方法的作用,更别说应用了.以下对Audio a ...

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

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

  3. 代码验证浏览器是否支持html audio 和video

    <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8&quo ...

  4. HTML5 Audio/Video 标签,属性,方法,事件汇总

    HTML5 Audio/Video 标签,属性,方法,事件汇总 (转) 2011-06-28 13:16:48   <audio> 标签属性:src:音乐的URLpreload:预加载au ...

  5. html5 audio/video 的那些坑

    当我最近项目用到audio的时候,我们用到了jPlayer作为三方库. 功能实现了,暂停播放,进度条什么的,都很顺利的搞定了.后来考虑到当网速过慢时需要给播放按钮一个载入动画,然后就一发不可收拾了. ...

  6. [jPlayer] HTML5 Audio & Video for jQuery

    ---------------------------------------------------------------------------------------------------- ...

  7. html5 音频和视频(audio And video)

    1.音频和视频  Web 上的视频 直到现在,仍然不存在一项旨在网页上显示视频的标准. 今天,大多数视频是通过插件(比如 Flash)来显示的.然而,并非所有浏览器都拥有同样的插件. HTML5 规定 ...

  8. html5中的video标签和audio标签

    不管是否承认,flash早已不像过往那样如日中天了.亚马逊全面放弃flash.苹果放弃flash.安卓也放弃了移动端的flash支持.事实上flash已经不太适合web开发了,因为HTML5中的vid ...

  9. HTML5 Audio/Video 标签,属性,方法,事件汇总 (转)

    HTML5 Audio/Video 标签,属性,方法,事件   <audio> 标签属性:src:音乐的URLpreload:预加载autoplay:自动播放loop:循环播放contro ...

随机推荐

  1. Java集合的实现细节—Set集合和Map集合

    Set:代表无序.不可重复的集合 Map:代表key-value对集合,也称为关联数组 从表面上看,Set和Map相似性很少,但实际上可以说Map集合时Set集合的扩展. 1.Set集合和Map集合的 ...

  2. html5上传本地图片,在线预览及裁剪(filereader,canvas)

    1 我们常常需要上传头像,点击上传按钮时候需要预览一下,使用filereader方法无需和后台交互,代码如下: //本地图片在上传之前的预览效果 //图片上传预览 function previewIm ...

  3. SpringMVC接收复杂集合参数

    Spring MVC在接收集合请求参数时,需要在Controller方法的集合参数里前添加@RequestBody,而@RequestBody默认接收的enctype (MIME编码)是applica ...

  4. hdu 5396 Expression(区间dp)

    Problem Description Teacher Mai has n numbers a1,a2,⋯,anand n−1 operators("+", "-&quo ...

  5. css中的字体样式及元素样式

    css中的字体样式一般包含有就9中,常见的有7种.这7种依次为: 1.字体样式:font-family: 2.字体大小:font-size: 3.字体加粗:font-weight: 4.字体斜体:fo ...

  6. MVC笔记

    简要论述对MVC模式的理解,并简述ThinkPHP中的MVC模式是如何运行的 MVC(Model-View-Controller)应用程序结构被用来分析分布式应用程序的特征.这种抽象结构能有助于将应用 ...

  7. Sass函数--列表函数

    列表函数简介 列表函数主要包括一些对列表参数的函数使用,主要包括以下几种: length($list):返回一个列表的长度值: nth($list, $n):返回一个列表中指定的某个标签值  join ...

  8. (转)javascript深入理解js闭包

    一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变量. Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量 ...

  9. String类的使用说明

    (1)Length()取一个字符串的长度:public int length(); public calss StringLength1{ public static void main(String ...

  10. C/C++中的隐式类型转换

    代码: #include <iostream> #include <cstdio> using namespace std; int main(int argc,char* a ...