Free Video player Videojs Chinese tutorials

Source: Internet
Author: User
Tags event listener

Video.js is a web video player that supports both HTML5 and flash two playback modes. More about the introduction of Video.js, you can visit the official website, I have also written an article about the use of video.js, interested can point here, read the number of people are quite a lot of, some enthusiastic readers even gave me a small dozen reward, although not much money, but very touched. In the last few days, I received several netizens ' private messages, and asked some questions about the use of VIDEOJS. I do not remember what videojs look like, out of the trust of others to me, and looked back over the previous article, or the time of 2014, and now VIDEOJS version has been updated to 6.0.0, the code has been reconstructed, the original introduction of the method, is now not well-informed. So I went to the official website to re-write a copy of the code, after learning to rewrite a tutorial.

How to get the code for VIDEOJS

Videojs source is hosted on the github.com above, generally speaking, the master branch corresponds to the latest version, click on the right of the green clone or download button can be the source of the download, but the latest code is not necessarily a stable version, so here is a little trick, We can choose the most recent tag to download, which is a lot more secure.

After downloading the corresponding source code, after the general decompression, you can see a dist directory, which is the author for us packaged code, there are generally two versions, compressed and uncompressed version, but unfortunately, this version is actually not packaged good code, it seems that only to complete this step. The method is very simple, generally look at how to use or quick start, there will be a description of how to generate a release package release method. But again disappointed, still did not find the relevant introduction. It seems that only the last option is employed. Go directly to the Package.json file and find scripts:

 "homepage": "Http://videojs.com", "Author": "Steve Heffernan", "scripts": {"changelog": "Conventional-changelog -P videojs-i changelog.md-s "," Build ":" Grunt Dist "," Change ":" Grunt Chg-add "," clean ":" Grunt Clean "," gr Unt ":" Grunt "," Lint ":" Vjsstandard "," Start ":" Grunt Dev "," Test ":" Grunt Test "," Docs ":" NPM run Docs:lint & amp;& NPM Run Docs:api "," JSDoc ":" JSDoc "," Predocs:api ":" Node-e \ "var s=require (' Shelljs '), d=[' Docs/api '];S.R M ('-rf ', d); \ "", "Docs:api": "Jsdoc-c. Jsdoc.json", "Postdocs:api": "Node./build/fix-api-docs.js", "Docs:lint": "Remark--'./**/*.md '", "Docs:fix": "Remark--output--'./**/*.md '", "Babel": "Babel src/js-d es5", "Prepublis H ":" Not-in-install && run-p Docs:api Build | | In-install "," Prepush ":" NPM run lint----errors "," Version ":" Node build/version.js && git add changelog.m D "}, 

There are a lot of scripts, I just want to build a method here, the author actually use Grunt, to install grunt, need to install Nodejs, and then through the NPM install installation build dependency, after completion, you can run NPM run build The script gets the required code.

See this result, without errors, the explanation succeeds. Open the Video.js-master directory again, there will be a dist directory, inside the necessary JS and CSS files, there is a examples directory.

Video.js and Video-js.css are the files that need to be used next. If it is put on the line, you can use the compressed version (plus. min suffix) directly.

If these you do not want to do, then I am here to provide ready-made downloads, click here to download videojs.6.0.0

How to play a video using Videojs

Imagine that if we did not use this VIDEOJS to play the web video, the simplest way is to use the HTML5 video tag. Just like this:

123 <videoid="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="640" height="264"  poster="http://vjs.zencdn.net/v/oceans.png">        <sourcesrc="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4"></video>

Videojs is used in a similar way, but since we have some control or enactment of the video with Videojs, we first introduce the two files in the head tag to Video.js and Video-js.css. Then you can use the VIDEOJS. The simplest start:

var player = Videojs (' example_video_1 ');

When this page is refreshed again, the default video appearance becomes the default style of Videojs (usually called the skin).

VIDEOJS is a global function that can receive three parameters (Id,options,onready): The first parameter is the ID of the video tag, which is compatible with the previous way, and it is possible to use ' # ' +id, for example

Videojs (' #example_video_1 '); The second parameter is the configuration option, which can be given in addition to this, by means of the data-setup= ' {} ' property in the video tag. If you do not know what to pass, then this options can be omitted directly, but if you want to use the third parameter onready, the options cannot be omitted directly, you must use {} for the placeholder. The third parameter is actually a callback function after the completion of the VIDEOJS initialization, in which you can use this to refer to the Videojs instance object. Perform operations such as This.play (), This.pause (), This.on (' ended '):

 

Here is an official example of Onready:

var options = {};var player = Videojs (' example_video_1 ', options, function Onplayerready () {  Videojs.log (' Player is ready! ') );  In this context, the "This" is the player of the created by Video.js.
Note that the context of this place, ' this ' is pointing to an instance of Video.js to a player like this.play (); How is an event listener?
How do I use event snooping? This.on (' ended ', function () { Videojs.log (' Play ended! ');});

For video playback, the commonly used features are:

1. Play This.play ()

2. Stop--Video has no Stop method, you can use pause pause to get the same effect

3. Suspension of This.pause ()

4. Destruction of This.dispose ()

5. Monitor This.on (' click ', fn)

6. Trigger Event This.trigger (' Dispose ')

....

The "This" above refers to the execution in the Onplayerready function.

How to configure parameters for Videojs

There are two ways to change the behavior of Videojs:

1. By adding the Data-setup property of the video tag: <video data-setup= ' {"AutoPlay": "True",.....} '

2. var player = Videojs (' Example_video_1 ', {autoplay:true,....}), passing directly to the options

Because the first way is written in the HTML tag, through Json.parse parsing, low performance, but also easy to error. Individuals are more inclined to Method 2.

Here are a number of configuration parameters for options: http://docs.videojs.com/tutorial-options.html

Several commonly used items are:

If the Autoplay:true/false player is ready, automatically plays "Default false" if true /present as an attribute, begins playback when the player is Rea Dy

controls : true/false 是否拥有控制条 【默认true】,如果设为false ,那么只能通过api进行控制了。也就是说界面上不会出现任何控制按钮       

Height: Length of the video container, string or number unit pixels such as: height:300 or Height: ' 300px '

Width: Length of the video container, string or number unit pixels

Loop:true/false If video playback is finished, loop

Muted:true/false is muted

Poster: The video screen displayed before playback is automatically removed after playback begins. Usually pass in a URL

Preload: Pre-load

' Auto ' automatically

' Metadata ' metadata information, such as video length, size, etc.

' None ' does not preload any data until the user starts playing to start the download

Children:array | Object Optional subcomponents inherit from the underlying component component, and the order in the array affects the order in which the components are created.

The following code creates a player with just Bigplaybutton and//controlbar child components.//The following way only using Bigplaybutton and ControlBar two sub-components Videojs (' My-player ', {  children: [    ' Bigplaybutton ',    ' ControlBar '  ]});

  

Sources:array resource File

Videojs (' My-player ', {  sources: [{    src: '//path/to/video.mp4 ',    type: ' Video/mp4 '  }, {    src: '// PATH/TO/VIDEO.WEBM ',    type: ' VIDEO/WEBM '  }]});

Equivalent to the form in HTML:

<video ...>  <source src= "//path/to/video.mp4" type= "Video/mp4" >  <source src= "//path/to/ VIDEO.WEBM "type=" VIDEO/WEBM "></video>

techOrder: Array 使用哪种技术播放,可选值有‘html5‘,‘flash‘  默认为[‘html5‘], 注意: 在v6.0.0 及以上的版本中,默认不包含flash的使用代码。如果要使用flash播放的,需要手动引入flash相关逻辑的代码。且需要指定swf文件的路径。

Globally specify the location of the swf file  videojs.options.flash.swf = ' video-js.swf '//Create a player.var player = Videojs (' example_video_1 ' {teachorder:[' flash ']},function () {Console.log (This)});

There are also items that can be configured, such as plugins: Automatically initializing the plugin to be loaded, and then studying it when it is used. For general applications, understanding the usage of the above configuration items should be sufficient for a burst. However, the needs of the project are often perverted (custom requirements), which requires an in-depth study and understanding of the "Component"-components of an important part of VIDEOJS.

How to customize Videojs components

There is a netizen asked me, how to add a video title in the video, play when automatically hide the title, the user focus on the player or pause when the display title?

I think the right thing to do is to do it in a component way. Source Address

Where index.html is implemented in a violent way, update.html is implemented in a component way

 

Get the Component base class from video.js//gets a base component from Videojs var Component = videojs.getcomponent (' Component ');//The Videojs.extend function is used to assist with inheritance. in//an ES6 environment, ' class TitleBar extends Component ' would work//identically.//Videojs.extend method is used to implement inheritance, equivalent to the ES6 environment Class TitleBar extends Component usage var titlebar = videojs.extend (Component, {//The constructor of a Component receives T  Wo arguments:the//player It is associated with and an object of options.  This constructor receives two parameters://player will be used to correlate the options in the Parameters constructor:function (player, options) {//It is important to invoke the    Superclass before anything else,//To get all the features of any of the box!    It is important to call the constructor of the parent class before doing anything else,//so that all the attributes of the parent component will be out of the box in the subassembly.    Component.apply (this, arguments);    If a ' text ' option is passed in, update the text content of//the component. If the Text property is passed in the options, the text that updates the component displays if (Options.text) {This.updatetextcontenT (Options.text);  }},//The ' createel ' function of a component creates its DOM element. Create a DOM element Createel:function () {return videojs.dom.createEl (' div ', {///prefixing classes of elements within      A player with "vjs-"//are a convention used in video.js.  The style name that begins with the element plus vjs-is the VIDEOJS built-in style className: ' Vjs-title-bar '});  },//This function could is called at any time to update the text//contents of the component.    This method can call Updatetextcontent:function (text) {//If no text is provided, default to "text Unknown" when any need to update the content of this component    If the Text property is not provided in the options, the text unknow if (typeof text!== ' string ') is displayed by default {text = ' text Unknown ';    }//Use Video.js utility DOM methods to manipulate the content//of the component ' s element.    Use the DOM method provided by Video.js to manipulate component elements Videojs.dom.emptyEl (This.el ());  Videojs.dom.appendContent (This.el (), text); }});//Register the component with Video.js, so it can be used in players.//registered in VIDEOJScomponents, you can use OH. Videojs.registercomponent (' titlebar ', titlebar);  

Although the code is much more in the way of components, in the long run, the readability of this method is better and is the official recommended way.

Summary

Most of us are reluctant to build wheels, especially when there are ready-made wheels. A wheel like Videojs, with its own strength, is difficult to achieve this maturity. So my only idea is to try to understand it, at least carefully read its API, understand its basic usage, but also to be able to do a certain degree of expansion and transformation as needed. If it is easy to use, to be able to write your own extension (component), then you need to have a basic understanding of its implementation principle. However, to do this, just look at the API is not enough, you must combine the source to learn. And the best way to learn is to try, when necessary to carry out breakpoint tracking, focus on the method of focusing on learning, take notes, draw sketches. Finally thanks to the spirit or cash rewards friends, write me the impetus of this article.

Free Video player Videojs Chinese tutorials

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.