Build your own HTML5 video player

Source: Internet
Author: User

Some time ago to re-learn the video part of the HTML5, previously just stuck on the use of tags, this time decided to drill into the relevant APIs, and use these APIs to create a simple video player. The so-called "Build Your Own" is to rewrite the control bar section of the video tag, including play, Pause, progress and volume control, full screen and other functions, and customize the style of the control bar. This is the demo address of my own video player (please Open with chrome):

http://animademo.sinaapp.com/html5_video/(^-^: Click the link in the middle mouse button and open it in the new tab)

This is the code address of the player and can also be downloaded after viewing:
Https://github.com/animabear/html5_video_player

Now I'll step through the process of building your own HTML5 video player:

One, the main API involved in the custom control bar

1. Video Playback related API

Read-only properties:
Video.duration: Duration of the entire media file, unit s
Video.paused: Returns True if the media file is paused, or true by default if playback has not started
Video.ended: Returns True if the media file is finished playing

Writable Properties:
Video.currenttime: Returns the time, in S, from the start of playback to the present. During playback, set CurrentTime to search and navigate to a specific location in the media file
Video.volume: Sets the relative value of the audio volume between 0.0 and 1.0, or queries the current volume relative value
Video.muted: Detects whether the current is muted, is true, sets mute or mutes the file

Control functions:
Video.play (): Play video file
Video.pause (): Pause the video file in the playback state
Video.canplaytype (): test whether the video element supports files of the given MIME type

Listener events:
Ontimeupdate: Triggers the event when a video.currenttime change occurs

2. Full-screen Control API
Note: Here only WebKit full-screen API, this code does not do compatibility, the main application of WebKit some advanced API and chrome pseudo-elements, so please use Chrome to open the presentation address.

Video.webkitrequestfullscreen (): Full screen display
Document.webkitcancelfullscreen (): Exit full Screen
Document.webkitisfullscreen: Returns True if currently in full-screen state, otherwise false
Document.addeventlistener (' Webkitfullscreenchange ', handler): This event is triggered when switching between full-screen and non-full-screen states

3. local file Read API
Description: My this video player supports adding video files from the local playback, supported formats within the standard range of HTML5 video playback supported by the WebKit browser. The local file read API is the new standard for HTML5.

Window. Url.createobjecturl: File is an object that returns an object URL to a file that can be accessed by the URL.

window.URL.createObjectURL(file);
Second, the video player control bar style implementation

For the convenience of the diagram, I use pure to help the layout, a very concise CSS framework, in fact, it is useless to how much. As for those control buttons, with the help of CSS3 's @font-face, I use the icon-font to achieve.

Icon-font is actually the so-called icon font, the design of the SVG format image into the relevant platform, the generation of font files or base64 encoded strings, and then refer to these custom font files in the page or INSERT Base64 encoded string.

Here to recommend a good platform, Icomoon, with the help of the platform of the Icomoon App, you can do the above operations. And the platform also provides a number of excellent font library, I am using the existing. This is a good choice for kids ' shoes that don't make a design and don't want to spend time looking for pictures. In fact, Icon-font is mainly used to reduce the request file size.

Third, the video element initialization work

The HTML structure of the video element:

<video id="player" width="600" height="450">您的浏览器不支持HTML5 <source src="./videos/echo-hereweare.mp4"></source> <!-- 提供默认的播放视频 --></video>

JS initialization of the video element:

var $player = $(‘#player‘);var player = $player[0]; //方便使用dom原生的api
Four, the control bar on the implementation of the functions of each controller

1. Play, pause and stop
Html:

<span id="play" class="icon icon-play"></span><span id="stop" class="icon icon-stop"></span>

Javascript:

$play. On (' Click ',function () {if (player.paused) {player.play (); //Play $ (this). Removeclass ( ' Icon-play '). AddClass ( ' icon-pause '); } else {player.pause (); //pause $ (this). Removeclass ( ' Icon-play ');}); $stop. On ( "click", function< Span class= "Hljs-params" > () {player.currenttime = 0; //stop playing $innerBar. CSS ( ' width ', 0 + " Span class= "hljs-string" > ' px '); }); 

2. Playback Progress control bar and playback time display
1) Play Progress control bar:
This part to achieve two functions, one is to click on a point on the control bar, the video can jump to the corresponding point in time, the other is to have a click after the control bar to have a corresponding display (feedback), indicating the current position.
Html:

<div id="progressBar" class="controlBar">    <div id="innerBar" class="controlInner"></div></div>

Javascript:

  $progressBar. On ( ' click ', function (e) {var w = $ (this). Width (), x = E.offsetx; window.per = (x/w). toFixed (3); //global variable var duration = player.duration; player.currenttime = ( Duration * window.per). ToFixed (0); $innerBar. CSS ( ' px '); //Feedback});             

The implementation of the progress control bar, to use a very key attribute: E.offsetx, in Firefox does not have this attribute, but there is a similar e.layerx, specifically can be consulted MDN. E.offsetx indicates that the position of the mouse pointer is relative to the x-coordinate of the object that triggered the event, knowing the width of the value and the progress bar, you can calculate the percentage of the current click Position, and then you can reset the video's currenttime based on the percentage to achieve progress control.

Note: The reason here is to introduce a global variable window.per to record the current playing progress percentage, because after switching to full-screen, the length of the control bar will be longer, after exiting the full screen, the length of the control bar will be shortened, so the corresponding inner progress bar (to show the progress of) the length of the change, after the implementation of full screen /non-fullscreen switch is specified. Also, since this percentage is changed during playback, the global variable window.per is constantly updated:
Javascript:

   $player. On ( ' timeupdate ', Span class= "hljs-function" >function () { //... (represents the omitted code) var w =  $progressBar. width (); if (player.duration) {var per = (Player.currenttime/ player.duration). toFixed (3); window.per = per;} else {per = 0;}  $innerBar. css ( ' width ', (w * per). ToFixed ( 0) +  ' px '); //...});             

2) Playback time display
This is relatively simple, mainly a time conversion, or the use of the above Timeupdate event
Html:

<span id="timer">0:00</span>

Javascript:

$player. On (' Timeupdate ',function () { Number of seconds conversion var time = player.currentTime.toFixed (1), minutes = Math.floor (Time/60)% 60), seconds = Math.floor (Time% 60); if (Seconds < 10) {seconds =  ' 0 ' + Seconds }  $timer. Text (minutes +  ': ' + seconds); //... (Update control bar section) if (player.ended) {//play complete $ Play.removeclass ( "Icon-pause"). AddClass ( ' Icon-play ');});    

Note: When you have finished playing, remember to reset the play button's icon to the playback state

3. Volume Control
1) Mute and Unmute
Html:

<span id="volume" class="icon icon-volume"></span>

Javascript:

$volume. On ( ' click ', function () {if (player.muted) {player.muted = FALSE; $ (this). Removeclass ( ' Icon-volume-mute '). AddClass ( ' Icon-volume '); $volumeInner. CSS (100 +  '% ' ); //Volume control bar back to full blood} else {player.muted = true; $ (this ). Removeclass ( ' Icon-volume '). addclass ( ' Icon-volume-mute '); $volumeInner. CSS (0);});     

2) Volume Control bar
The volume control bar and the playback progress control bar are actually the same, the only difference is that here we change the value of the Video.volume.
Html:

<div id="volume-control" class="controlBar">    <div id="volume-inner" class="controlInner"></div></div>

Javascript:

$volumeControl    .on(‘click‘, function(e) {        var w = $(this).width(), x = e.offsetX; window.vol = (x / w).toFixed(1); //全局变量 player.volume = window.vol; $volumeInner.css(‘width‘, x + ‘px‘); });

The reason for setting global variables here is ibid.

4. File Upload button
Here are two things to do, one is to upload the file and generate the object URL, and the other is to determine whether the browser can play the format of the file before uploading. Because the browser supports less playback format, the more common is the MP4, is a tentative function of it.
Html:

<span id="upload" class="icon icon-upload"></span><!-- ... 省略代码 --><input type="file" id="file">

Css:

#file {    visibility: hidden;}

Javascript:

$upload. On (' Click ',function() {$file. Trigger (' click '); });$file. On (' Change ',function (e) {var file = E.target.files[0], Canplaytype = Player.canplaytype (File.type); //determine if the format is supported if (canplaytype = = =  Maybe ' | | Canplaytype = = =  ' probably ') {src = window. Url.createobjecturl (file); PLAYER.SRC = src;  $play. Removeclass ( ' Icon-pause '). addclass (  Icon-play '); //newly opened video in paused status Player.onload =  function () {window. Url.revokeobjecturl (SRC); }; } else {alert ( "browser does not support the file format you chose")});     

Note: In order to completely freely define the style of the upload button, a small trick is to trigger the Click event of the Real commit button (input[type= ' file ') by clicking on the Custom Upload button, and then hiding the real submit button in the CSS. About the file read API, you can go to the MDN to learn more.

5, full-screen/non-full-screen switching and related control
Switching between fullscreen and non-fullscreen, using the WebKit API is easy to implement
Html:

<span id="expand" class="icon icon-expand"></span>

Javascript:

$expand    .on(‘click‘, function() {        if (!document.webkitIsFullScreen) { player.webkitRequestFullScreen(); //全屏 $(this).removeClass(‘icon-expand‘).addClass(‘icon-contract‘); } else { document.webkitCancelFullScreen(); $(this).removeClass(‘icon-contract‘).addClass(‘icon-expand‘); } });

Now there are two more key questions, one is how to hide the default control bar of the video tag in full screen and display its own control bar, and the second is to play the progress control bar and the volume control bar display state adjustment, which has been mentioned earlier.

1) How to hide the default control bar of the video tag in full screen
On this issue, I just started to search in Chinese for a long time, did not find the relevant content, so I try to use the Google "How to hide video controls in HTML5", the results came out of the third is what I want, have to sigh that some resources can only be searched through English.

This article is very clear to describe this problem, the basic principle to take advantage of browser-specific pseudo-elements, which also refers to the concept of Shadow dom, very good article, I will not repeat:
Hiding Native HTML5 Video Controls in Full-screen Mode

2) Change the width of the control progress bar (inner progress bar) during Fullscreen/non-fullscreen switching
Javascript:

$(document)    .on(‘webkitfullscreenchange‘, function(e) { var w = $progressBar.width(), w1 = $volumeControl.width(); if (window.per) { $innerBar.css(‘width‘, (window.per * w).toFixed(0) + ‘px‘); } if (window.vol) { $volumeInner.css(‘width‘, (window.vol * w1).toFixed(0) + ‘px‘) } });

The two global variables defined earlier here come in handy.



All the code can be downloaded on GitHub, in fact, it is a very simple demo, the main purpose or want to learn a bit more HTML5 video, after all, can not only stay in a label to use. Finally recommend an article, is "to build" their own HTML5 music player, others do that is the real cow, it is worth learning:
Http://www.feelcss.com/html5-music-player-design.html

Build your own HTML5 video player

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.