search
HomeWeb Front-endH5 TutorialImplement an example of an HTML5 music player

Technical points: ES6+Webpack+HTML5 Audio+Sass

Here, we will learn step by step how to implement an H5 music player from scratch.

First let’s take a look at the final implementation effect: Demo link

Then let’s get to the point:

  1. To make a music player you need to I know very well how audio is played on the Web. The audio tag of HTML5 is usually used.
    Regarding the audio tag, it has a large number of attributes, methods and events. Here I will give a general introduction.

    Attributes:
    src: required, audio source;
    controls: common, the browser's default audio control panel will be displayed after setting, and the audio tag will be hidden by default if not set;
    autoplay: common, Automatically play audio after setting (not supported by mobile terminal);
    loop: common, audio will play in loop after setting;
    preload: common, set audio preloading (not supported by mobile terminal);
    volume: rare , sets or returns the audio size, the value is a floating point number between 0-1 (not supported by mobile terminals);
    muted: rare, sets or returns the mute state;
    duration: rare, returns the audio duration;
    currentTime: rare, sets or returns the current playback time;
    paused: rare, returns the current playback status, whether to pause;
    buffered: rare, a TimeRanges object containing buffered time period information, that is, loading progress . This object contains an attribute length, which returns a number starting from 0 to indicate how many audio segments are currently buffered; it also contains two methods, start and end, which each need to pass in a parameter, that is, which segment of the audio has been loaded. Start from 0. start returns the starting time of the segment, and end returns the end time of the segment. For example: Input 0, the start of the first paragraph is 0, the end time is 17, the unit is seconds;
    attributes are introduced here, there may be some less used attributes such as: playbackRate, etc., during video playback It may be used, but I won’t explain it yet.

    Method:
    play(): Start playing audio;
    pause(): Pause playing audio;

    Event:
    canplay: The current audio can start playing (only Part of the buffered is loaded, but not all of it is loaded);
    canplaythrough: it can be played without pause (that is, all the audio is loaded);
    durationchange: the audio duration changes;
    ended: the playback ends;
    error: An error occurred;
    pause: Playback is paused;
    play: Playback starts;
    progress: Triggered during the audio download process. During the event triggering process, the loading progress can be obtained by accessing the buffered attribute of audio;
    seeking: Triggered during audio jump, that is, when currentTime is modified;
    seeked: Triggered when audio jump is completed, that is, when currentTime is modified;
    timeupdate: Triggered during audio playback, and the currentTime attribute is updated synchronously;
    Events are introduced here. There may be some less commonly used events that will not be explained yet.

    Finally, let’s explain the event flow triggered by an audio from the beginning of loading to the end of playback, as well as the attributes we can operate in different time periods:
    loadstart: start loading;
    durationchange: Obtain the audio duration (the duration attribute can be obtained at this time);
    progress: Audio downloading (will be triggered along with the download process, and the buffered attribute can be obtained at this time);
    canplay: The loaded audio is enough to start playing ( Playback will also be triggered after each pause);
    canplaythrough: All audios are loaded;
    timeupdate: During playback (the currentTime attribute is updated synchronously);
    seeking: The current playback progress is being modified (i.e. To modify the currentTime attribute);
    seeked: modification of the current playback progress is completed;
    ended: playback is completed;
    This is the general event flow of the entire audio, there may be some less used events that are not listed.
    During the event triggering process, there are some properties that can be set before the audio starts loading, such as: controls, loop, volume, etc.;

  2. Determine the overall structure:
    Because we publish it as a plug-in on npm for others to use, we use an object-oriented approach to code writing, and because users have different needs, we design A large number of APIs and configuration items are exposed from the beginning to meet the needs of most users.
    Because I am more accustomed to the syntax of es6, I developed the entire process based on es6. At the same time, for the sake of development efficiency, I used sass to write css. Finally, I used webpack and webpack-dev-server to compile es6. And sass, project packaging, build local server.


  3. Determine the player UI and interaction:
    Everyone may have their own ideas about the interface, so I won’t go into details here. I will use the player UI I made as an example to break it down

    From the interface, we can see the most basic functions required by a player:
    Play/pause, cover/song title/singer display, playback progress bar/loading progress bar/progress operation function , loop mode switching, progress text update/song duration, mute/volume size control, list display status control, click list item to switch songs function
    Combined with the starting point of providing configuration items and APIs that we want to meet user needs, we can get Figure out the configuration items and exposed API items we want to design:
    Configuration items: whether automatic playback is turned on, the display status of the default song list, and the settings of the default loop mode
    API: play/pause/toggle, loop mode Switch, mute/restore, switch list display status, previous song/next song/switch to song, destroy current instance


  4. Establish the project structure , start coding:
    Because we use webpack, we package the css directly into js so that it can be used as a plug-in for users:

    require('./skPlayer.scss');

    Extract the public method, in There are many public methods in the player that may need to be removed, such as: when you click on the playback progress bar and volume progress bar, you need to calculate the distance between the mouse and the left end of the progress bar to perform a progress jump. The time in seconds is obtained from duratin. Time conversion into standard time format, etc.:

    const Util = {
        leftDistance: (el) => {
            let left = el.offsetLeft;
            let scrollLeft;while (el.offsetParent) {
                el = el.offsetParent;
                left += el.offsetLeft;
            }
            scrollLeft = document.body.scrollLeft + document.documentElement.scrollLeft;return left - scrollLeft;
        },
        timeFormat: (time) => {
            let tempMin = parseInt(time / 60);
            let tempSec = parseInt(time % 60);
            let curMin = tempMin  {return (percent * 100).toFixed(2) + '%';
        },
        ajax: (option) => {
            option.beforeSend && option.beforeSend();
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = () => {if(xhr.readyState === 4){if(xhr.status >= 200 && xhr.status 
    View Code

    Due to the initial design, playback was considered The uniqueness of the server is designed so that only one instance can exist. A global variable is set to determine whether the instance currently exists:

    let instance = false;

    In the case of using ES6, we put the main logic Inside the constructor, put the generality and API inside the public function:

    class skPlayer {
        constructor(option){
        }
    
        template(){
        }
    
        init(){
        }
    
        bind(){
        }
    
        prev(){
        }
    
        next(){
        }
    
        switchMusic(index){
        }
    
        play(){
        }
    
        pause(){
        }
    
        toggle(){
        }
    
        toggleList(){
        }
    
        toggleMute(){
        }
    
        switchMode(){
        }
    
        destroy(){
        }
    }
    View Code

    Instance judgment, if there is an empty object without a prototype, an instance with a prototype is returned by default in the ES6 constructor:

            if(instance){
                console.error('SKPlayer只能存在一个实例!');return Object.create(null);
            }else{
                instance = true;
            }

    Initialize the configuration items, and the default configuration is merged with the user configuration:

            const defaultOption = {
                ...
            };this.option = Object.assign({},defaultOption,option);

    Bind common properties to instances:

            this.root = this.option.element;this.type = this.option.music.type;this.music = this.option.music.source;this.isMobile = /mobile/i.test(window.navigator.userAgent);

    Some public API internal this points to the instance by default, but in order to reduce The amount of code is to call a set of codes for functions and APIs on the operation interface. When binding events, the point of this will change, so bind this through bind. Of course, you can also use arrow functions when binding events:

            this.toggle = this.toggle.bind(this);this.toggleList = this.toggleList.bind(this);this.toggleMute = this.toggleMute.bind(this);this.switchMode = this.switchMode.bind(this);

    Next, we use the ES6 string template to start generating HTML and insert it into the page:

                this.root.innerHTML = this.template();

    Next, initialize, initialization process Lieutenant General binds commonly used DOM nodes, initializes configuration items, and initializes the operation interface:

                this.init();
        init(){this.dom = {
                cover: this.root.querySelector('.skPlayer-cover'),
                playbutton: this.root.querySelector('.skPlayer-play-btn'),
                name: this.root.querySelector('.skPlayer-name'),
                author: this.root.querySelector('.skPlayer-author'),
                timeline_total: this.root.querySelector('.skPlayer-percent'),
                timeline_loaded: this.root.querySelector('.skPlayer-line-loading'),
                timeline_played: this.root.querySelector('.skPlayer-percent .skPlayer-line'),
                timetext_total: this.root.querySelector('.skPlayer-total'),
                timetext_played: this.root.querySelector('.skPlayer-cur'),
                volumebutton: this.root.querySelector('.skPlayer-icon'),
                volumeline_total: this.root.querySelector('.skPlayer-volume .skPlayer-percent'),
                volumeline_value: this.root.querySelector('.skPlayer-volume .skPlayer-line'),
                switchbutton: this.root.querySelector('.skPlayer-list-switch'),
                modebutton: this.root.querySelector('.skPlayer-mode'),
                musiclist: this.root.querySelector('.skPlayer-list'),
                musicitem: this.root.querySelectorAll('.skPlayer-list li')
            };this.audio = this.root.querySelector('.skPlayer-source');if(this.option.listshow){this.root.className = 'skPlayer-list-on';
            }if(this.option.mode === 'singleloop'){this.audio.loop = true;
            }this.dom.musicitem[0].className = 'skPlayer-curMusic';
        }
    View Code

    Event binding, mainly binding audio events and operation panel events:

                this.bind();
        bind(){this.updateLine = () => {
                let percent = this.audio.buffered.length ? (this.audio.buffered.end(this.audio.buffered.length - 1) / this.audio.duration) : 0;this.dom.timeline_loaded.style.width = Util.percentFormat(percent);
            };// this.audio.addEventListener('load', (e) => {//     if(this.option.autoplay && this.isMobile){//         this.play();//     }// });this.audio.addEventListener('durationchange', (e) => {this.dom.timetext_total.innerHTML = Util.timeFormat(this.audio.duration);this.updateLine();
            });this.audio.addEventListener('progress', (e) => {this.updateLine();
            });this.audio.addEventListener('canplay', (e) => {if(this.option.autoplay && !this.isMobile){this.play();
                }
            });this.audio.addEventListener('timeupdate', (e) => {
                let percent = this.audio.currentTime / this.audio.duration;this.dom.timeline_played.style.width = Util.percentFormat(percent);this.dom.timetext_played.innerHTML = Util.timeFormat(this.audio.currentTime);
            });//this.audio.addEventListener('seeked', (e) => {//    this.play();//});this.audio.addEventListener('ended', (e) => {this.next();
            });this.dom.playbutton.addEventListener('click', this.toggle);this.dom.switchbutton.addEventListener('click', this.toggleList);if(!this.isMobile){this.dom.volumebutton.addEventListener('click', this.toggleMute);
            }this.dom.modebutton.addEventListener('click', this.switchMode);this.dom.musiclist.addEventListener('click', (e) => {
                let target,index,curIndex;if(e.target.tagName.toUpperCase() === 'LI'){
                    target = e.target;
                }else{
                    target = e.target.parentElement;
                }
                index = parseInt(target.getAttribute('data-index'));
                curIndex = parseInt(this.dom.musiclist.querySelector('.skPlayer-curMusic').getAttribute('data-index'));if(index === curIndex){this.play();
                }else{this.switchMusic(index + 1);
                }
            });this.dom.timeline_total.addEventListener('click', (event) => {
                let e = event || window.event;
                let percent = (e.clientX - Util.leftDistance(this.dom.timeline_total)) / this.dom.timeline_total.clientWidth;if(!isNaN(this.audio.duration)){this.dom.timeline_played.style.width = Util.percentFormat(percent);this.dom.timetext_played.innerHTML = Util.timeFormat(percent * this.audio.duration);this.audio.currentTime = percent * this.audio.duration;
                }
            });if(!this.isMobile){this.dom.volumeline_total.addEventListener('click', (event) => {
                    let e = event || window.event;
                    let percent = (e.clientX - Util.leftDistance(this.dom.volumeline_total)) / this.dom.volumeline_total.clientWidth;this.dom.volumeline_value.style.width = Util.percentFormat(percent);this.audio.volume = percent;if(this.audio.muted){this.toggleMute();
                    }
                });
            }
        }
    View Code

    至此,核心代码基本完成,接下来就是自己根据需要完成API部分。
    最后我们暴露模块:

    module.exports = skPlayer;

    一个HTML5音乐播放器就大功告成了 ~ !

The above is the detailed content of Implement an example of an HTML5 music 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
The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.