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:
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.;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.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-
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.:
View Codeconst?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 ? ('0' + tempMin) : tempMin; let curSec = tempSec < 10 ? ('0' + tempSec) : tempSec;return curMin + ':' + 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('GET',option.url); xhr.send(null); } };
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:
View Codeclass skPlayer { constructor(option){ } template(){ } init(){ } bind(){ } prev(){ } next(){ } switchMusic(index){ } play(){ } pause(){ } toggle(){ } toggleList(){ } toggleMute(){ } switchMode(){ } destroy(){ } }
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只能存在一個實(shí)例!');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();
View Codeinit(){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'; }
Event binding, mainly binding audio events and operation panel events:
this.bind();
View Codebind(){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(); ????????????????} ????????????}); ????????} ????}
至此,核心代碼基本完成,接下來就是自己根據(jù)需要完成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!

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)

HTML5, CSS and JavaScript should be efficiently combined with semantic tags, reasonable loading order and decoupling design. 1. Use HTML5 semantic tags, such as improving structural clarity and maintainability, which is conducive to SEO and barrier-free access; 2. CSS should be placed in, use external files and split by module to avoid inline styles and delayed loading problems; 3. JavaScript is recommended to be introduced in front, and use defer or async to load asynchronously to avoid blocking rendering; 4. Reduce strong dependence between the three, drive behavior through data-* attributes and class name control status, and improve collaboration efficiency through unified naming specifications. These methods can effectively optimize page performance and collaborate with teams.

It is a block-level element, suitable for layout; it is an inline element, suitable for wrapping text content. 1. Exclusively occupy a line, width, height and margins can be set, which are often used in structural layout; 2. No line breaks, the size is determined by the content, and is suitable for local text styles or dynamic operations; 3. When choosing, it should be judged based on whether the content needs independent space; 4. It cannot be nested and is not suitable for layout; 5. Priority is given to the use of semantic labels to improve structural clarity and accessibility.

HTML5introducednewinputtypesthatenhanceformfunctionalityanduserexperiencebyimprovingvalidation,UI,andmobilekeyboardlayouts.1.emailvalidatesemailaddressesandsupportsmultipleentries.2.urlchecksforvalidwebaddressesandtriggersURL-optimizedkeyboards.3.num

To get the user's current location, use the HTML5 GeolocationAPI. This API provides information such as latitude and longitude after user authorization. The core method is getCurrentPosition(), which requires successful and error callbacks to be handled; at the same time, pay attention to the HTTPS prerequisite, user authorization mechanism and error code processing. ① Call getCurrentPosition to get the position once, and an error callback will be triggered if it fails; ② The user must authorize it, otherwise it cannot be obtained and may no longer be prompted; ③ Error processing should distinguish between rejection, timeout, location unavailable, etc.; ④ Enable high-precision, set timeout time, etc., and can be configured through the third parameter; ⑤ The online environment must use HTTPS, otherwise it may be restricted by the browser.

The difference between async and defer is the execution timing of the script. async allows scripts to be downloaded in parallel and executed immediately after downloading, without guaranteeing the execution order; defer executes scripts in order after HTML parsing is completed. Both avoid blocking HTML parsing. Using async is suitable for standalone scripts such as analyzing code; defer is suitable for scenarios where you need to access the DOM or rely on other scripts.

ConfirmyourlocationsupportsInstagrammusicanddisableanyVPN;2.UpdatetheInstagramappviatheAppStoreorGooglePlayStore;3.Switchtoapersonalorcreatoraccountifusingabusinessaccount;4.CleartheappcacheonAndroidorreinstalltheapponiOS;5.Ensureastableinternetconne

The key to using radio buttons in HTML5 is to understand how they work and correctly organize the code structure. 1. The name attribute of each radio button must be the same to achieve mutually exclusive selection; 2. Use label tags to improve accessibility and click experience; 3. It is recommended to wrap each option in a div or label to enhance structural clarity and style control; 4. Set default selections through the checked attribute; 5. The value value should be concise and meaningful, which is convenient for form submission processing; 6. The style can be customized through CSS, but the function needs to be ensured to be normal. Mastering these key points can effectively avoid common problems and improve the effectiveness of use.

The core difference between localStorage and sessionStorage lies in data persistence and scope. 1. Data life cycle: localStorage data is stored for a long time unless manually cleared, and sessionStorage data is cleared after closing the tab; 2. Scope difference: localStorage is shared among all tabs on the same website, and sessionStorage is stored independently; 3. Usage scenario: localStorage is suitable for saving long-term data such as user preferences and login status, sessionStorage is suitable for temporary form data or single session process; 4. API consistency: two operation methods
