Use HTML5 for video playback

Source: Internet
Author: User
Tags rewind

Most of the time, Web pages use Flash to play video. In the current environment of Flash, HTML5 brings us a solution--<video> tag for video playback in the web.

In HTML5, embedded media can be supported via HTML tags "audio" and "video", enabling developers to easily embed media into HTML documents.

Video format

Currently, the video element supports three types of videos:

    • OGG = Ogg file with Theora video encoding and Vorbis audio encoding
    • MPEG4 = MPEG 4 file with H + video encoding and AAC audio encoding
    • WebM = WebM file with VP8 video encoding and Vorbis audio encoding
Embed Media

HTML5 embedded media is as simple as using tags to embed images, you just need a <video> tag to:

<video src="../video/2.ogg" controls></video>

src property to specify the video file you want to play, the controls property can display the video playback control (not shown by default).

You can set content in the <video> tab, which will appear when the browser does not support <video>:

<audio src="audio.ogg" controls autoplay loop><p>你的浏览器不支持video标签</p></audio>
Playback properties

You can set some properties in the video tag to make it easy to control the player.

For example, the specified player size is 640px * 480px:

<video src="../video/2.ogg" height="480" width="640" controls>    <p>你的浏览器不支持video标签</p></video>

The units of the height and width properties are pixels, or pixels. If these properties are set, Space is reserved for the video when the page loads. If these properties are not set, the browser cannot predetermine the size of the video so that it cannot retain the appropriate space for the video. As a result, the layout also changes during page loading.

Let's say the following example:

<video src="../video/2.ogg" height="480" width="640" autoplay loop muted controls>    <p>你的浏览器不支持video标签</p></video>

In this example, three additional attributes are added:
The AutoPlay property allows the video to be played automatically when it is ready;
The Loop property specifies that the video is looped, that is, playing again from the beginning, and the muted property makes it mute by default when playing.

Let's look at an example:

<video src="../video/2.ogg" height="480" width="640" preloader="auto" poster="../video/show.png" controls>    <p>你的浏览器不支持video标签</p></video>

There are two properties: Preloader tells the video to load when the page loads and prepares it for playback. If you use "autoplay", the property is ignored. Preloader has three attribute values to set:

    • "None" does not buffer files
    • "Auto" buffered audio files
    • "Metadata" only the metadata of the buffer file poster set the video display image, including the pre-play display image and the downloaded display image, if this property is not set, normally the video area before playback is black.

The above three examples contain the HTML5 <video> tags to all the currently added properties, organized as follows:

    • Height player
    • Width player widths
    • AutoPlay video is ready to play automatically when finished
    • Controls display the playback control that contains action components such as play, progress bar, full screen, and so on
    • Loop Set Video loop playback
    • Muted Mute playback video
    • Preload video is loaded when the page loads and ready to play. If you use "autoplay", the property is ignored.
    • Poster video display images, i.e. images displayed before or during video playback
<source> tags

You can use the <source> tag within the <video> tag to specify multiple playback files to provide a supported encoding format for different browsers. For example:

<video controls>  <source src="../video/2.ogg" type="video/ogg">  <source src="../video/2.mp4" type="video/mp4">  <p>你的浏览器不支持video标签</p></video>

The browser will load 2.ogg first, and if the Ogg format is not supported or the video does not exist, it will load 2. MP4, and so on.

<source> tag, you need to specify the file via SRC, using the Type property to specify the file format.

<track> tags

To specify a caption file, you can use the <track> tag; track is used in the same way as source.

<video controls>  <source src="../video/2.ogg" type="video/ogg">  <source src="../video/2.mp4" type="video/mp4">  <track kind="captions" src="sampleCaptions.vtt" srclang="en">  <track kind="descriptions" src="sampleDescriptions.vtt" srclang="en">  <track kind="chapters" src="sampleChapters.vtt" srclang="en">   <p>你的浏览器不支持video标签</p></video>

<track> tags can be used to specify subtitle files or other files that contain text.

<track> Tag properties include:

    • SRC source file
    • KIND specifies the purpose for which the file is used, the default value is subtitles, and the optional values are:
      • Subtitles definition This file is a subtitle file, is familiar with the video bottom subtitles
      • Captions a short description that will be displayed in the player
      • The text description of the descriptions video content, suitable for the audio description provided by the blind or when the video is not visible.
      • Chapters definition section for navigating media resources
      • Metadata the content that is provided to the script, not visible to the user
    • Label assigns a name to the caption file for use by the browser, which is used when the browser needs to list the available subtitle files.
    • Srclang the language of the track, this property is required when the kind property value is "subtitles"

Although the <track> tag provides a rich text content support for video, the browser's support rate for track is not optimistic at this time.

The above simply introduces the use of video tags in HTML5. The next article plans to introduce video event-related content. For more in-depth insight, you can view the documentation here.

use HTML5 for video playback (ii)When you play a video, you often need to control playback. At this point we need to use the methods, properties, and events of the HTML5 <video> element.
Pause/Play

The play () and Pause () methods of video are used to play and pause videos respectively.

By judging the paused property of the video tag, you can know the playback status of the current movie. Paused is false when the video is in playback state, paused is true when it is paused.

Example:

<video id="video" preloader poster="../video/show.png" height="480" width="640">    <source src="../video/trailer.MP4" type="video/mp4"></video><button id="play_btn" type="button"></button>
var v = document.getElementById(‘video‘);var playBtn = document.getElementById(‘play_btn‘);playBtn.textContent = ‘>‘;playBtn.addEventListener("click", function(){    if(v.paused){      v.play();      playBtn.textContent = ‘||‘;    }else{      v.pause();      playBtn.textContent = ‘>‘;    }});
Volume

You can control the playback volume by using the volume property.
The value of the volume is between 0~1.

<video id="video" preloader poster="../video/show.png" height="480" width="640">    <source src="../video/trailer.MP4" type="video/mp4"></video><div>    音量<button id="vol_inc_btn" type="button">+</button>    <button id="vol_dec_btn" type="button">-</button></div>
var v = document.getElementById(‘video‘);var volIncBtn = document.getElementById(‘vol_inc_btn‘);var volDecBtn = document.getElementById(‘vol_dec_btn‘);volIncBtn.addEventListener("click", function(){  v.volume > 0.9?v.volume = 1:v.volume += 0.1;})volDecBtn.addEventListener("click", function(){  v.volume < 0.1?v.volume = 0:v.volume -= 0.1;})

The muted property indicates whether it is muted. A value of true, the video is muted.

<button id="muted_btn" type="button">静音</button>
var mutedBtn = document.getElementById(‘muted_btn‘);mutedBtn.addEventListener("click", function(){  v.muted = !v.muted;  mutedBtn.textContent = v.muted?‘恢复‘:‘静音‘;})
Play time

The CurrentTime property of video is used to get the current playing position. The Duration property represents the length of the current resource. With these two properties, the time display of the current moment/total length format can be realized.

<font id="now_time" size="3"></font>/<font id="duration" size="3"></font>
var nowTime = document.getElementById(‘now_time‘);var duration = document.getElementById(‘duration‘);//初始值设为0nowTime.textContent = 0;duration.textContent = 0;//currentTime 和 duration 单位都是秒,我们写一个函数来将时间显示格式变为 mm:ss。function parseTime(time){  time = Math.floor(time);  var _m, _s;  _m = Math.floor(time/60);  _s = time - _m*60;  if(_m<10){    _m = ‘0‘ + _m;  }  if(_s<10){    _s = ‘0‘ + _s;  }  return _m + ‘:‘ + _s}v.addEventListener(‘timeupdate‘, function(){  nowTime.textContent = parseTime(v.currentTime);})v.addEventListener(‘loadedmetadata‘, function(){  console.log(‘loadedmetadata‘)  duration.textContent = parseTime(v.duration);})

Two events are used here: Timeupdate and Loadedmetadata.

The Timeupdate event is triggered when the playback time changes, where we listen for changes in playback time and then update the display synchronously.

The Loadedmetada is triggered when the resource length is successfully obtained.

Progress bar

The progress bar is standard in the player, and we can also implement the following progress bar function easily here.

<div id="progressWrap">    <div id="playProgress">    </div></div>
var progressWrap = document.getElementById("progressWrap");var playProgress = document.getElementById("playProgress");//计算当前进度条显示长度,利用前面说过的 currentTime 和 duration。function getProgress(){  var percent = v.currentTime / v.duration;  playProgress.style.width = percent * (progressWrap.offsetWidth) + "px";}// 鼠标在播放条上点击时进行捕获并进行处理function videoSeek(e){    if(v.paused || v.ended){        v.play();    }    enhanceVideoSeek(e);}function enhanceVideoSeek(e){    var length = e.pageX - progressWrap.offsetLeft;    var percent = length / progressWrap.offsetWidth;    playProgress.style.width = percent * (progressWrap.offsetWidth) + "px";    v.currentTime = percent * v.duration;}progressWrap.addEventListener(‘click‘, function(e){  videoSeek(e);})v.addEventListener(‘timeupdate‘, function(){  getProgress();})
Playback speed

The Playbackrate property represents the current playback speed. Normal playback speed is 1. By changing the value of the playbackrate, you can adjust the video playback speed.

For example, we implement a fast forward function that allows playback speed to switch between normal/twice times/4 times times:

<button id="speed_up" type="button">快进</button>
var speedUpBtn = document.getElementById(‘speed_up‘);var _speed = 1;speedUpBtn.addEventListener(‘click‘, function(){  changeSpeed();});function changeSpeed () {  _speed = _speed * 2;  if(_speed>4){    _speed = 1;  }  v.playbackRate = _speed;  speedUpBtn.textContent = _speed===1?‘快进‘:‘快进x‘ + _speed;}

With the fast-forward function, generally also have a quick-rewind function. Here you can use the previously mentioned currenttime to simple implementation.

<button id="back" type="button">快退</button>
var backBtn = document.getElementById(‘back‘);var _back_speed = 1;var _t;backBtn.addEventListener(‘click‘, function(){  _back_speed = _back_speed * 2;  if(_back_speed>4){    v.playbackRate = 1;    _back_speed = 1;    clearInterval(_t);  }else{    v.playbackRate = 0;    clearInterval(_t);    //通过计时器来不断改变当前播放位置,实现后退的功能    _t = setInterval(function(){      v.currentTime -= _back_speed * 0.1;    },100)  }  backBtn.textContent = _back_speed===1?‘快退‘:‘快退x‘ + _back_speed;})
Load state

The load status of a resource can be monitored through event loadstart and Loadeddata.

The Loadstart event is triggered when the resource starts to load. When the load is complete, the Loadeddata event is triggered. If the load fails, the error event is triggered.

<p id="load_state"></p>
var loadState = document.getElementById(‘load_state‘);v.addEventListener(‘loadstart‘, function(){  loadState.textContent = ‘视频加载中。。。‘;})v.addEventListener(‘loadeddata‘, function(){  loadState.textContent = ‘加载完毕。‘;})v.addEventListener(‘error‘, function(){  loadState.textContent = ‘加载失败。‘;})
Fullscreen

Mainstream browsers are now basically full-screen, but different browser implementations are not the same:

Webkit (works in Safari5.1 and Chrome 15)
Element.webkitrequestfullscreen ();
Document.webkitcancelfullscreen ();

Firefox
Element.mozrequestfullscreen ();
Document.mozcancelfullscreen ();

Proposal
Element.requestfullscreen ();
Document.exitfullscreen ();

To achieve full-screen effects, you only need to call these methods.

<button id="fullscreen" type="button">全屏</button>
function requestFullScreen(de) {  if (de.requestFullscreen) {    de.requestFullscreen();  } else if (de.mozRequestFullScreen) {    de.mozRequestFullScreen();  } else if (de.webkitRequestFullScreen) {    de.webkitRequestFullScreen();  }}var fullscreen = document.getElementById(‘fullscreen‘);fullscreen.addEventListener(‘click‘, function(){  requestFullScreen(v);})

At this point basically implemented a simple player's control components, including play, pause, time display, volume adjustment, progress bar, fast forward, rewind, full screen and so on. Our player sheet is like this:


Haha, very rough, but with the style of the words will be much better ~

In addition, video also provides a lot of events in the above example is not used, listed below, need to enrich the function can be viewed at any time ~

Full Code Chinteo/html5videodemo

Use HTML5 for video playback

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.