"Turn" an open source free cross-browser video player--videojs usage Introduction

Source: Internet
Author: User

Special Note: I blog part of the reference network other blogs, but I have personally written and verified through. If you find that the blog has errors, please prompt to avoid misleading other people, thank you! Welcome reprint, but remember to indicate the source of the article: http://www.cnblogs.com/mao2080/

The video features in the recent project need to be fully compatible with the browser, so the video functions previously implemented with HTML5 need to be transformed. Over the internet, try to try, in all the video player, the number of its most practical. First, let's look at its advantages:

1. It is open source free and you can easily get its latest code on GitHub.

2. It's very easy to use it, just take a few seconds to rack up a video playback page.

3. It is almost compatible with all browsers, and HTML5 is preferred, and in unsupported browsers It is automatically played using Flash.

4. The interface can be customized, pure JavaScript and CSS built. The description document is also very detailed.

Here is a simple way to use the website:

<! DOCTYPE html>
<src="Http://video-js.zencoder.com/oceans-clip.mp4type=' video/mp4'/>  


Such an example is enough for a movie site to be used for it. But our needs are often not just that simple. For example, I now want to force the use of Flash playback on the PC to how to set?

There are two ways of doing this:

First of all, set by the Data-setup property of HTML.

<video id= "Example_video_1" class= "Video-js vjs-default-skin vjs-big-play-centered"  controls preload= "Auto" Width= "640" height= "poster="  http://video-js.zencoder.com/oceans-clip.png "data-setup="  {techorder: [ "Flash", "HTML5"]} ' >  ...</video>

The second is the use of javascript:

  Videojs (' #example_video_1 ', {    techorder: ["Flash", "HTML5"]  },function () {    })

Of course, the official documentation says it automatically detects if HTML5 is supported and automatically uses Flash playback when not supported.

With the popularity of single-page applications, many times, when we initialize VIDEOJS, there is no node on the page to store video. This time, Videojs also thought for us, we only need to set empty Data-setup properties on it. Then make the following statement in JS:

Videojs (document.getElementById (' example_video_1 '), {}, function () {  //This is functionally the same as the previous Example.});

In other words, the first position, we can directly pass the DOM node reference is also possible.

At this point we found that the play button is in the upper-left corner by default, and the official says it does not obscure the wonderful parts of the content, but if we want to put it in the middle, it's easy to handle. Adding a vjs-big-play-centered style to the video tag is fine.

<video id= "Example_video_1" class= "Video-js vjs-default-skin vjs-big-play-centered"  controls preload= "Auto" Width= "640" height= "poster=" http://video-js.zencoder.com/oceans-clip.png "data-setup=  ' {" Example_ Option ": true} ' >  ...</video>

If we want it to play automatically, it is very easy to add a autoplay on it, or data-setup= ' {"AutoPlay": true} ', through JS is the same truth. It's very simple and doesn't show up. Officially, because of the HTML5 standard, it is not recommended to write autoplay= "true" or controls= "true", which is used in previous versions of HTML5.

The default control bar will have a lot of components I don't need to use, more than subtitles, for optimization, we can define which components to display:

var player = Videojs ("Example_video_1", {    "Techorder": ["Flash", "html"],    "autoplay": false,    ControlBar: {        Captionsbutton:false,        Chaptersbutton:false,        livedisplay:false,        playbackratemenubutton:false,        Subtitlesbutton:false      }}, Function () {    this.on (' Loadeddata ', function () {        Console.log (this)    })    This.on (' ended ', function () {         this.pause ();         This.hide ()})    ;

Our optimization is for option because some nodes we do not need to create, which are created by default, which obviously affect efficiency, here is a usage of my project:

Videojs (' Example_video_1 ', {        techorder: ["HTML5", "flash"],        children: {            bigplaybutton:false,            Texttrackdisplay:false,            Posterimage:false,            errordisplay:false,            controlbar: {                Captionsbutton: False,                Chaptersbutton:false,                subtitlesbutton:false,                livedisplay:false,                Playbackratemenubutton:false            }        }    },function () {        Console.log (this)    });

Compared to the DOM node, a lot less, feel the start significantly faster. It's refreshing to watch.

Print this to look under:

The two are one to 9 objects in total, resulting in 9 nodes, with only 3 child elements on the outside. The default control section generates 14 external 9 child elements. The optimization effect is very obvious.

When initializing, the following parameters are commonly used:

Https://github.com/videojs/video.js/blob/stable/docs/guides/options.md

AutoPlay

Auto Play

<AutoPlay >or{"autoplay": true}
Preload

Pre-load Resources

<preload >or{"preload": "Auto"}
Poster

Video thumbnail image

< poster= "Myposter.jpg" ...>or{"poster": "Myposter.jpg"}  
Loop

Auto Cycle

<loop ... >or{"loop": "True"}
Width

The width attribute sets the display width of the video.

<width= "640" ... >or{"width": 640}  
Height

The height attribute sets the display height of the video.

<height= "480" ... >or{"height": 480}  
Component Options

Functional Components (example shows how to remove the mute button)

= Videojs (' Video-id', {  ControlBar: {Mutetogglefalse}});   

VIDEOJS has many components, such as sounds, play buttons, subtitles, time, progress bars, and so on, and their structure in HTML is similar to this:

Player    posterimage    texttrackdisplay    loadingspinner    bigplaybutton    controlbar        playtoggle        Fullscreentoggle        Currenttimedisplay        timedivider        durationdisplay        remainingtimedisplay        Progresscontrol            SeekBar              loadprogressbar              playprogressbar              seekhandle        volumecontrol            volumebar                Volumelevel                volumehandle        mutetoggle

Usually the HTML5 will load faster than flash, so we usually prefer to use HTML5, and write what we want to do in the callback. Like what:

Videojs ("Example_video_1"). Ready (function () {  var myplayer = this;  Example:start playing the video.  Myplayer.play ();});

It should be stressed that if you use Flash first, then you in the local mode, you want to use HTTP access, otherwise you can not see anything.

For more API calls see here HTTPS://GITHUB.COM/VIDEOJS/VIDEO.JS/BLOB/STABLE/DOCS/API/VJS.PLAYER.MD

Methodsautoplaybufferedbufferedendbufferedpercentcancelfullscreen Deprecatedcontrolscurrentsrccurrenttimecurrenttypedispose//cleaning up durationended//End error//error Exitfullscreen// Exit full-screen initisfullscreen deprecated obsolete isfullscreenlanguageloadloop//loop muted silent pause pause paused// Detect paused status Playplaybackrateposter//static picture Preloadremainingtime//remaining time Requestfullscreen Deprecatedrequestfullscreenseekingsrcvolumeaddchild Inheritedaddclass Inheritedbuildcssclass Inheritedchildren Inheritedcontentel inheritedcreateel inheriteddimensions Inheritedel inheritedenabletouchactivity inheritedgetChild Inheritedgetchildbyid inheritedhasclass inheritedheight inheritedhide inheritedid InheritedinitChildren Inheritedname inheritedoff Inheritedon inheritedone inheritedoptions inheritedplayer inheritedready Inheritedremovechild inheritedremoveclass inheritedshow Inheritedtrigger inheritedtriggerready inheritedwidth Inherited

Here I say a few common methods: Clean dispose,hide () hide, show () display, play () play, Pause (), El () to get the video element, pause a few books on the almost.

The last thing to say is the event. The official alert events are as follows:

Eventsdurationchangeendedfirstplayfullscreenchangeloadedalldataloadeddataloadedmetadataloadstartpauseplayprogressseekedse Ekingtimeupdatevolumechangewaitingresize inherited

We often have play play, pause pauses, ended end, error errors, loadeddata data loading complete

VIDEOJS plug-in mechanism, I use the player's control bar to add a close button as an example, show if using plug-ins to achieve our own desired function.

Videojs. POWEROFF = Videojs. Button.extend ({/* @constructor */init:function (player, options) {Videojs.                 Button.call (this, player, options);               OnClick is the default event, do not need to be fixed by the State, otherwise it will be two times//this.on (' click ', This.onclick);            }             }); /* This function is called if X button is clicked */Videojs. PowerOff.prototype.onClick = function () {console.log (' ddd ')
Add here to do what you want to do}; /* Create X button */var Createpoweroffbutton = function () {var props = {CL Assname: ' Vjs-off-button vjs-control ', InnerHTML: ' <div class= ' vjs-control-content ' >X</div> ' , Role: ' button ', ' aria-live ': ' Polite ', tabindex:0 }; return videojs.Component.prototype.createEl (null, props); }; /* ADD X button to the control bar */var X; Videojs.plugin (' PowerOff ', function () {var options = {' el ': Createpoweroffbutton ()}; X = new Videojs. POWEROFF (this, options); This.controlBar.el (). AppendChild (X.el ()); });

When calling, add the name of the plugin to the parameter:

var player = Videojs ("Example_video_1", {      plugins: {PowerOff: {}}}, function () {    });

Did you see the "X" we added? What, your x is in the middle? Forgot to tell you that the style of this place to add itself, mine is such

. Vjs-default-skin. Vjs-control.vjs-off-button {         display:block;         font-size:1.5em;         Line-height:2;         position:relative;         top:0;         Float:right;         left:10px;         height:100%;         Text-align:center;         Cursor:pointer;         }

is not quite nice.

In practice, I find there are some inconsistencies between flash mode and HTML5 mode.

For example, in Flash mode, after the player pauses or hides, call the paused () method error: VIDEOJS:Video.js:paused unavailable on Flash playback technology element.

After calling Hide (), the show () method is called, and in flash mode, playback is automatically called, and the HTML5 mode does not. For this, the workaround is to specify Autoplay:false in option so that the behavior is consistent.

Using Videojs I have found several places to be aware of:

1: The Full-screen button is not valid on an IFRAME-loaded page. Of course later confirmed not videojs problem, is the IFRAME to add allowfullscreen attribute.

2: There are too many problems in flash mode, more than the repeated call to pause () will be error, after hide () call paused () will error.

3: Do not attempt to play audio in flash mode, although there are plug-ins to support, but a lot of problems. HTML5 mode I did not test.

Videojs in Flash mode, the following situations are conflicting:
1. Video calling Hide () in the broadcast causes an internal error, and if pause () and hide () are called first, then the call to pause () also causes an internal error. In a similar situation, call Dispose ()
2. In the case of video is hide, going to call paused () will produce an internal error
3. In the hide state, calling show () and then calling play will generate an internal error
4. If the file does not exist, an internal error will result if you do not call Dispose.

To sum up, for a single page application, Videojs when hidden, the internal state of the loss of the situation, will lead to a series of problems. The solution is to create one at a time. Close on to clean up. After testing, this pattern is no longer a mistake.

Only in this way, as an open source free product, has been quite good.

Reference website

Http://www.cnblogs.com/afrog/p/4115377.html

"Turn" an open source free cross-browser video player--videojs usage Introduction

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.