Home Web Front-end H5 Tutorial HTML5 video tag (player) study notes (2): playback control_html5 tutorial skills

HTML5 video tag (player) study notes (2): playback control_html5 tutorial skills

May 16, 2016 pm 03:46 PM
html5 video player Playback control Label

The previous article introduced some work that needs to be done to initialize the html5 tag video (player), and how to use the html5 player simply and quickly. This article will focus on how to use JS to operate the video tag, and also It is how to perform some simple and basic operations on video, including playing and pausing the player, reading and setting the volume, and other write-related operations, thus starting the expansion of the player.

Table of contents of this article:

1. Get the total duration of the video
2. Play and pause
3. Get the video playing time and set the play point
4. Get and set the volume

First, get the total duration of the video

When operating the player (video), the first thing you need to get is some information about the video, one of which is the total duration. In addition to the content, the total duration is also the first thing to be displayed. Before operating the video, add an ID to the video tag so that we can easily obtain the video element

Copy code
The code is as follows:


After setting an ID, you can start the operation. To get the total duration, you need to use an event of the video - loadedmetadata. The triggering of this event indicates that the metadata (some basic information of the media) has been loaded. Use addEventListener Listening events

Copy code
The code is as follows:

var myVideo = document.getElementById( 'myVideo');//Get the video element
myVideo.addEventListener("loadedmetadata", function(){
//Code to be executed
});
Okay, it’s already listened to. Then the next thing to do is to get the total duration, which is actually an attribute-duration
var myVideo = document.getElementById('myVideo')//Get the video element
,tol = 0
;
myVideo.addEventListener("loadedmetadata", function(){
tol = myVideo.duration;//Get the total duration
});

It should be noted that the unit of the total duration obtained is seconds, which should be converted as needed when displayed. 

Second, play, pause

The most basic function for the player is play and pause. After obtaining the total duration, the next operation is play and pause. The two methods of video used at this time are play and pause

Copy the code
The code is as follows:

var myVideo = document.getElementById('myVideo')//Get the video element
, tol = 0
;
myVideo.addEventListener("loadedmetadata", function(){
tol = myVideo.duration;//Get the total duration
});

//Play
function play(){
myVideo.play();
}

//Pause
function pause(){
myVideo.pause();
}


It should be noted that the play method is run after the playback is completed. will be played from the beginning.

Third, get the playback time of the video and set the playback point

After the player can play and pause, the next thing you need to see is how long the video has been playing and what time point it has been played. This operation is very similar to getting the total duration. It requires listening to an event and getting the value of an attribute. Then the timeupdate event and currentTime attribute of the video are used

Copy code
The code is as follows:

//When the playback time point is updated
myVideo.addEventListener("timeupdate", function(){
var currentTime = myVideo.currentTime;//Get the current playback time
console.log(currentTime);//Print in the debugger
});

After running, you will see a lot of data on the console...

We often receive a request, that is, it has been 10 minutes since we watched it last time. This time we want to start watching it from the tenth minute. Then we need to set the play point at this time. The currentTime attribute is still used to set the play point. , the currentTime attribute is readable and writable. It should be noted that the unit of the set value is seconds. If the playback point is not in seconds, it must be converted

Copy the code
The code is as follows:

//Set the play point
function playBySeconds(num){
myVideo.currentTime = num;
}

Fourth, obtaining and setting the volume

The player can pause and play during the playback process. It knows where it is playing now and can start playing from a certain point in time. Then the next operation is the volume. This is similar to the third point. You can directly use the volume attribute to obtain the volume. However, what we will also introduce here is the trigger event for volume change. In the future, we need to customize the UI for use, that is, the volumechange event

Copy code
The code is as follows:

//When the volume changes
myVideo.addEventListener("volumechange" , function(){
var volume = myVideo.volume;//Get the current volume
console.log(volume);//Print in the debugger
});

When you change the volume through the control bar, you will see a lot of data in the debugger. It should be noted that the range of volume is 0~1, and percentages are generally used in the UI, so conversion is required when necessary.

The volume can be set by changing the attribute, which is similar to the playback time point, except that the volume is set with the volume attribute

Copy code
The code is as follows:

//Set the volume
function setVol(num){
myVideo.volume = num;
}

The following is the complete code:

Copy the code
The code is as follows:




Video step2




<script><br>var myVideo = document.getElementById('myVideo')//Get the video element <br> ,tol = 0 //Total duration<br>;<br>myVideo.addEventListener("loadedmetadata", function(){<br> tol = myVideo.duration;//Get the total duration<br>});</p> <p>//Play<br>function play(){ <br> myVideo.play();<br>}</p> <p>//Pause<br>function pause(){ <br> myVideo.pause();<br>}</p> <p>//When the playback time point is updated<br>myVideo.addEventListener("timeupdate", function(){<br> var currentTime = myVideo.currentTime;//Get the current playback time<br> console.log(currentTime );//Print in debugger<br>});</p> <p>//Set play point<br>function playBySeconds(num){ <br> myVideo.currentTime = num;<br>}</p> <p>//When the volume changes<br>myVideo.addEventListener("volumechange", function(){<br> var volume = myVideo.volume;//Get the current volume<br> console.log(volume);/ /Print in debugger<br>});</p> <p>//Set volume<br>function setVol(num){ <br> myVideo.volume = num;<br>}<br></script>

< ;/html>

Summary: Use these four steps to understand the basic operations of the html5 tag video (player), and these operations are mainly to monitor video events and manipulate video attributes through JS It is completed by reading and writing. If you are familiar with these four points, you can use the player flexibly, and then adjust it according to the application scenario.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1600
276
What is the aside element for in HTML5? What is the aside element for in HTML5? Aug 12, 2025 pm 04:37 PM

Theelementshouldbeusedforcontenttangentiallyrelatedtothemaincontent,suchassidebars,pullquotes,definitions,advertisements,orrelatedlinks;2.Itcanbeplacedinsideoroutsideanarticledependingoncontext;3.ItisasemanticelementthatenhancesaccessibilityandSEObyp

How to create a simple HTML5 webpage How to create a simple HTML5 webpage Aug 12, 2025 am 11:51 AM

To create a simple HTML5 web page, you need to first use the declaration document type, and then build a basic structure containing, and, which sets the character encoding, viewport and title, add visible content such as title, paragraph, link, pictures and lists. Save it as a .html file and open it directly in the browser for viewing, without server support. This is the basis of a complete and effective HTML5 page.

What is the draggable attribute in HTML5 What is the draggable attribute in HTML5 Aug 12, 2025 am 09:50 AM

ThedraggableattributeinHTML5specifieswhetheranelementcanbedragged,withvalues"true","false",oranemptystring(sameas"true").2.Settingdraggable="true"enablesdrag-and-dropforanyelement,butJavaScripteventlistenerslik

How do you use the autofocus attribute in HTML5? How do you use the autofocus attribute in HTML5? Aug 14, 2025 pm 06:47 PM

Theautofocusattributeautomaticallyfocusesaformelementwhenapageloads.2.Itisabooleanattribute,sonovalueisneeded—justincludeautofocusinthetag.3.Onlyoneelementperpageshoulduseittoavoidunpredictablebehavior.4.Itworksoninput,textarea,select,andbuttonelemen

How to create a custom checkbox with HTML5 How to create a custom checkbox with HTML5 Aug 16, 2025 am 07:05 AM

To create a custom checkbox, you must first use an HTML structure with label to ensure accessibility; 2. Hide the default checkbox through CSS but retain its functionality; 3. Use pseudo-elements and pseudo-classes to draw the selected state on the custom .checkmark elements; 4. Add hover, focus and select styles to enhance interactive feedback; 5. Keep native inputs present to support keyboard navigation and screen readers, and ultimately achieve beautiful and accessible custom checkboxes.

How to use the nav tag for navigation links in HTML5 How to use the nav tag for navigation links in HTML5 Aug 15, 2025 am 05:55 AM

ThetaginHTML5isusedtodefineasectionofmajornavigationlinks,providingsemanticstructureandimprovingaccessibilityandSEO;itshouldwrapprimarynavigationelementslikemenusortablesofcontents,noteverylinkonapage,andcanbeenhancedwithARIAlabelssuchasaria-label=&q

What is a definition list in HTML5? What is a definition list in HTML5? Aug 20, 2025 pm 02:01 PM

AdefinitionlistinHTML5iscreatedusingtheelementtogroupterms()withtheirdefinitions(),allowingmultipletermstoshareadefinitionoratermtohavemultipledefinitions,makingitidealforFAQs,glossaries,metadata,andcontactdetailswhileimprovingaccessibilityandSEOthro

How to defer non-critical CSS in an HTML5 page? How to defer non-critical CSS in an HTML5 page? Aug 12, 2025 am 12:15 AM

To effectively improve page loading performance, you need to inline the critical CSS first and load the non-critical CSS asynchronously; 1. Use tools or manually identify the critical CSS and inline it to; 2. Use rel="preload" to combine onload, JavaScript dynamic loading or requestIdleCallback asynchronously; 3. Use media attributes to delay loading of conditional styles such as print or topics; 4. Merge and compress non-critical CSS to reduce requests; you can use the media="print" technique to achieve JavaScript-free asynchronous loading, thereby significantly optimizing the first-screen rendering speed.

See all articles