search
HomeWeb Front-endH5 TutorialHTML5 VideoAPI, build your own Web video player

1. Basic knowledge

## 1. Usage

<video src="./video/mv.mp4">video>

 

Note: The audio and video elements must contain both start and end tags, and cannot be used

 2. Important HTML attributes

Controls: ontrol: If this attribute appears, controls are displayed to the user, such as a play button. The playback controls in each browser are different, but the purpose is the same. You can control the start and end, jump to a new position and adjust the volume

 

Autoplay: autoplay: If it appears With this attribute, the video will be played as soon as it is ready. If the autoplay attribute is not set, the audio file must be played when the user clicks the play button.

 

loop:loop: (loop playback) tells the browser to start playing again from the beginning when the audio reaches the end

 

preload:auto, mete, none: Tell the browser how to download the audio

  • auto: Tell the browser to download the entire file so that it can be played when the user clicks the play button. Of course, the download process occurs in the background, so web page visitors don't have to wait for the download to complete and can still view the web page as they wish.

  • meta: Tell the browser to get the data block at the beginning of the audio file first, which is enough to determine some basic information (such as the total duration of the audio)

  • none: ** Tells the browser not to download it beforehand. Using these values ​​appropriately can save bandwidth.

If the preload attribute is not set, the browser will decide whether to pre-download it. Different browsers handle this differently. Most browsers use auto as the default, but Firefox's default is metadata. However, please also note that this preload attribute is not a rule that must be strictly implemented, but is just a suggestion for the browser. Depending on the circumstances, the browser may ignore your settings. (Some older browsers will not care about the preload attribute.)

 3. Common events

Event name: Explanation

oncanplay : Script to run when the file is ready to start playing (when buffering is sufficient to start).

 ontimeupdate: A script that runs when the playback position changes (such as when the user fast-forwards to a different position in the media).

 

onended: A script that runs when the media has reached the end (can send a message like "Thanks for watching").

4. Commonly used methods

Method name: Explanation

play(): Start playing audio/video

 

pause():Pause the currently playing audio/video

 5. Commonly used API attributes

 Attribute name: Explanation

 

duration: Returns the length of the current audio/video (in seconds)

 

paused: Sets or returns whether the audio/video is paused

 

currentTime: Set or return the current playback position in the audio/video (in seconds)

 

ended: Return whether the playback of the audio/video has ended

For more attributes, events, and methods, please view w3school

2. Create your own player

We use JavaScript to control playback The behavior of the control (customized playback control) implements the following functions:

  • Use HTML+CSS to create your own playback control bar, and then position it at the bottom of the video

  • Video loading loading effect

  • ##Play, pause

  • Total duration and current playback duration display

  • Playback progress bar

  • Full screen display

## 1.
Playback controls

<figure>
    <figcaption>视频播放器figcaption>    <p>
        <video>video>        <p>
            
            <a>a>            
            </a><a>a>            
            <p>
                </p>
<p>p>                </p>
<p>p>                </p>
<p>p>            p>            
            </p>
<p>
                <span>00:00:00span> /                <span>00:00:00span>            p>            
        p>    p>figure></span></span></p></a></p></video></p></figcaption></figure>
The above is all HTML code, the .controls class is the playback control HTML, citing the CSS code:
<link><link>
In order to display the play button and other icons, I used the font icon

2. Video loading loading effect

Hide the video at the beginning, replace it with a background image, and then display the video when the video is loaded and ready to be played

CSS:

.player {    width: 720px;    height: 360px;    margin: 0 auto;    background: #000 url(../images/loading.gif) center/300px no-repeat;    position: relative;}
 video {    display: none;    height: 100%;    margin: 0 auto;

3. Play Function

Let’s start writing javascript code. First we get the DOM elements to be used:

var video = document.querySelector("video");var isPlay = document.querySelector(".switch");var expand = document.querySelector(".expand");var progress = document.querySelector(".progress");var loaded = document.querySelector(".progress > .loaded");var currPlayTime = document.querySelector(".timer > .current");var totalTime = document.querySelector(".timer > .total");
When the video can be played, display the video

//当视频可播放的时候video.oncanplay = function(){      //显示视频
      this.style.display = "block";      //显示视频总时长
      totalTime.innerHTML = getFormatTime(this.duration);
};

  4.播放、暂停

  点击播放按钮时显示暂停图标,在播放和暂停状态之间切换图标

//播放按钮控制isPlay.onclick = function(){        if(video.paused) {
            video.play();
        } else {
            video.pause();
        }        this.classList.toggle("fa-pause");
};

  5.总时长和当前播放时长显示

  前面代码中其实已经设置了相关代码,此时我们只需要把获取到的毫秒数转换成我们需要的时间格式即可,提供getFormatTime()函数:

function getFormatTime(time) {        var time = time  0; 
        var h = parseInt(time/3600),
            m = parseInt(time%3600/60),
            s = parseInt(time%60);
        h = h <p><strong>  6.播放进度条</strong></p><pre class='brush:php;toolbar:false;'>//播放进度video.ontimeupdate = function(){    var currTime = this.currentTime,    //当前播放时间
    duration = this.duration;       // 视频总时长
    //百分比
    var pre = currTime / duration * 100 + "%";    //显示进度条
    loaded.style.width = pre; 
     //显示当前播放进度时间
    currPlayTime.innerHTML = getFormatTime(currTime);
};

  这样就可以实时显示进度条了,此时,我们还需要点击进度条进行跳跃播放,即我们点击任意时间点视频跳转到当前时间点播放:

//跳跃播放progress.onclick = function(e){    var event = e  window.event;
    video.currentTime = (event.offsetX / this.offsetWidth) * video.duration;
};

  7.全屏显示

  这个功能可以使用HTML5提供的全局API:webkitRequestFullScreen实现,跟video无关:

//全屏expand.onclick = function(){
     video.webkitRequestFullScreen();
};

  经测试在firefox、IE下全屏功能不可用,这样正常了,全屏API是针对webkit内核的。

The above is the detailed content of HTML5 VideoAPI, build your own Web video player. 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
H5 Code: A Beginner's Guide to Web StructureH5 Code: A Beginner's Guide to Web StructureMay 08, 2025 am 12:15 AM

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

H5 Code Structure: Organizing Content for ReadabilityH5 Code Structure: Organizing Content for ReadabilityMay 07, 2025 am 12:06 AM

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment