search
HomeWeb Front-endH5 TutorialPlayback control of HTML5 video tag

Playback control of HTML5 video tag

Jun 11, 2018 pm 05:15 PM
html5videoplayerLabel

This article mainly introduces the playback control of the HTML5 video tag. This article explains how to obtain the total duration of the video, play, pause, obtain the playback time of the video, set the play point, obtain and set the volume, etc. Friends who need it can Refer to

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, that is How to perform some simple and basic operations on video, including playing and pausing the player, reading and setting the volume, and other 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 played time of the video and set the play point
4. Acquisition and setting of volume

First, get the total duration of the video

When operating the player (video), the first thing to get is the video Some information, 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

<video id="myVideo" controls preload="auto" width=300 height="165" 
     poster="http://img0.ph.126.net/I10JqUUJDmlEtE_XYl4hOg==/6608842237655242020.jpg" 
     src="http://www.w3cschool.cc/try/demo_source/mov_bbb.mp4">
    </video>

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

var myVideo = document.getElementById(&#39;myVideo&#39;);//获取video元素
myVideo.addEventListener("loadedmetadata", function(){
    //要执行的代码
});
     好了,已经监听了,那么接下来要做的就是获取总时长,其实就是一个属性-duration
var myVideo = document.getElementById(&#39;myVideo&#39;)//获取video元素
    ,tol = 0
;
myVideo.addEventListener("loadedmetadata", function(){
    tol = myVideo.duration;//获取总时长
});

. It should be noted that the unit of the total duration obtained is It is seconds. Convert it as needed when displaying.

Second, play and pause

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

var myVideo = document.getElementById(&#39;myVideo&#39;)//获取video元素
    ,tol = 0
;
myVideo.addEventListener("loadedmetadata", function(){
  tol = myVideo.duration;//获取总时长
 });</p>
<p> //播放
 function play(){ 
     myVideo.play();
 }</p>
<p> //暂停
 function pause(){ 
     myVideo.pause();
 }

It should be noted that running the play method after the playback ends will play it 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 played. , which time point is played. This operation is very similar to getting the total duration. It requires monitoring an event and getting the value of an attribute. Then the timeupdate event and currentTime attribute of the video are used.

//播放时间点更新时
myVideo.addEventListener("timeupdate", function(){
   var currentTime = myVideo.currentTime;//获取当前播放时间
   console.log(currentTime);//在调试器中打印
});

will be displayed on the console after running Seeing a lot of data...

We often receive a request, that is, it was 10 minutes ago when we saw it last time. This time we want to start watching it from the tenth minute. Then we need to set the playback point at this time. Now, 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 setting value is seconds. If the play point is not in seconds, it must be converted.

//设置播放点
function playBySeconds(num){ 
    myVideo.currentTime = num;
}

Fourth, volume acquisition and setting

The player can pause and play during playback, know where it is playing now and can start playing from a certain point in time, then The next thing to do is the volume. This is similar to the third point. You can directly use the volume attribute to obtain the volume. But here we also introduce the trigger event of volume change. In the future, you need to customize the UI for use, that is, the volumechange event

//音量改变时
myVideo.addEventListener("volumechange", function(){
   var volume = myVideo.volume;//获取当前音量
   console.log(volume);//在调试器中打印
});

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 attributes, which is similar to the playback time point, except that the volume is set with the volume attribute

//设置音量
function setVol(num){ 
   myVideo.volume = num;
}

The following is the complete code:




   Video step2
   


   
<script>
var myVideo = document.getElementById(&#39;myVideo&#39;)//获取video元素
   ,tol = 0 //总时长
;
myVideo.addEventListener("loadedmetadata", function(){
   tol = myVideo.duration;//获取总时长
});</p> <p>//播放
function play(){ 
   myVideo.play();
}</p> <p>//暂停
function pause(){ 
   myVideo.pause();
}</p> <p>//播放时间点更新时
myVideo.addEventListener(&quot;timeupdate&quot;, function(){
   var currentTime = myVideo.currentTime;//获取当前播放时间
   console.log(currentTime);//在调试器中打印
});</p> <p>//设置播放点
function playBySeconds(num){ 
   myVideo.currentTime = num;
}</p> <p>//音量改变时
myVideo.addEventListener(&quot;volumechange&quot;, function(){
   var volume = myVideo.volume;//获取当前音量
   console.log(volume);//在调试器中打印
});</p> <p>//设置音量
function setVol(num){ 
   myVideo.volume = num;
}
</script>


Summary: Use these four steps to understand the basic operations of the html5 tag video (player), and these operations are mainly completed through JS to monitor video events and read and write video attributes. Familiar These four points allow you to use the player flexibly and adjust it according to the application scenario.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Use HTML5 How to draw polygons such as triangles and rectangles with Canvas

About the control analysis of H5 new attributes audio and video

The above is the detailed content of Playback control of HTML5 video tag. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)