Home  >  Article  >  Web Front-end  >  Implement an example of an HTML5 music player

Implement an example of an HTML5 music player

零下一度
零下一度Original
2017-07-23 13:28:166100browse

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 < 10 ? (&#39;0&#39; + tempMin) : tempMin;
            let curSec = tempSec < 10 ? (&#39;0&#39; + tempSec) : tempSec;return curMin + &#39;:&#39; + curSec;
        },
        percentFormat: (percent) => {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 < 300){
                        option.success && option.success(xhr.responseText);
                    }else{
                        option.fail && option.fail(xhr.status);
                    }
                }
            };
            xhr.open(&#39;GET&#39;,option.url);
            xhr.send(null);
        }
    };
    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(&#39;SKPlayer只能存在一个实例!&#39;);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(&#39;.skPlayer-cover&#39;),
                playbutton: this.root.querySelector(&#39;.skPlayer-play-btn&#39;),
                name: this.root.querySelector(&#39;.skPlayer-name&#39;),
                author: this.root.querySelector(&#39;.skPlayer-author&#39;),
                timeline_total: this.root.querySelector(&#39;.skPlayer-percent&#39;),
                timeline_loaded: this.root.querySelector(&#39;.skPlayer-line-loading&#39;),
                timeline_played: this.root.querySelector(&#39;.skPlayer-percent .skPlayer-line&#39;),
                timetext_total: this.root.querySelector(&#39;.skPlayer-total&#39;),
                timetext_played: this.root.querySelector(&#39;.skPlayer-cur&#39;),
                volumebutton: this.root.querySelector(&#39;.skPlayer-icon&#39;),
                volumeline_total: this.root.querySelector(&#39;.skPlayer-volume .skPlayer-percent&#39;),
                volumeline_value: this.root.querySelector(&#39;.skPlayer-volume .skPlayer-line&#39;),
                switchbutton: this.root.querySelector(&#39;.skPlayer-list-switch&#39;),
                modebutton: this.root.querySelector(&#39;.skPlayer-mode&#39;),
                musiclist: this.root.querySelector(&#39;.skPlayer-list&#39;),
                musicitem: this.root.querySelectorAll(&#39;.skPlayer-list li&#39;)
            };this.audio = this.root.querySelector(&#39;.skPlayer-source&#39;);if(this.option.listshow){this.root.className = &#39;skPlayer-list-on&#39;;
            }if(this.option.mode === &#39;singleloop&#39;){this.audio.loop = true;
            }this.dom.musicitem[0].className = &#39;skPlayer-curMusic&#39;;
        }
    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
Previous article:Very good svg tutorialNext article:Very good svg tutorial