


HTML5 video tag (player) study notes (2): playback control_html5 tutorial skills
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
poster="http://img0.ph.126 .net/I10JqUUJDmlEtE_XYl4hOg==/6608842237655242020.jpg"
src="http://www.w3cschool.cc/try/demo_source/mov_bbb.mp4">
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
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
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
//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
//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
//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
//Set the volume
function setVol(num){
myVideo.volume = num;
}
The following is the complete code:
poster="http://img0.ph.126.net/I10JqUUJDmlEtE_XYl4hOg==/6608842237655242020.jpg"
src="http://www.w3cschool.cc/try /demo_source/mov_bbb.mp4">
<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.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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.

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

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

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.

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

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

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.
