This article mainly introduces the sample code of the native JS music player, which is shared with you as follows: RenderingMusic Player
Player attribute classification Classify the player's attributes and DOM elements according to the player's functions, and save the elements and attributes that implement the same function in the same object for easy management and operation const control = { //Store player control play: document.querySelector('#myplay'), ... index: 2, //The number of the song currently playing... } const audioFile = { //Store song files and related information file: document.getElementsByTagName('audio')[0], currentTime: 0, duration: 0, } const lyric = { // Lyrics display bar configuration ele: null, totalLyricRows: 0, currentRows: 0, rowsHeight: 0, } const modeControl = { //Play mode mode: ['sequential', 'random', 'single'], index: 0 } const songInfo = { // DOM container for storing song information name: document.querySelector('.song-name'), ... } Playback Controls Function: Control the music play and pause, previous song, next song, play completion and corresponding icon modification // Play and pause the music, control the previous and next song control.play.addEventListener('click',()=>{ control.isPlay = !control.isPlay; playerHandle(); } ); control.prev.addEventListener('click', prevHandle); control.next.addEventListener('click', nextHandle); audioFile.file.addEventListener('ended', nextHandle); function playerHandle() { const play = control.play; control.isPlay ? audioFile.file.play() : audioFile.file.pause(); if (control.isPlay) { //Play music, change icon and start playing animation play.classList.remove('songStop'); play.classList.add('songStart'); control.albumCover.classList.add('albumRotate'); control.albumCover.style.animationPlayState = 'running'; } else { //Pause the music, change the icon and pause the animation... } } function prevHandle() { // Reload songs according to the playback mode const modeIndex = modeControl.index; const songListLens = songList.length; if (modeIndex == 0) {//play in sequence let index = --control.index; index == -1 ? (index = songListLens - 1) : index; control.index = index % songListLens; } else if (modeIndex == 1) {//Random play const randomNum = Math.random() * (songListLens - 1); control.index = Math.round(randomNum); } else if (modeIndex == 2) {//single song} reload(songList); } function nextHandle() { const modeIndex = modeControl.index; const songListLens = songList.length; if (modeIndex == 0) {//Play in sequence control.index = ++control.index % songListLens; } else if (modeIndex == 1) {//Random play const randomNum = Math.random() * (songListLens - 1); control.index = Math.round(randomNum); } else if (modeIndex == 2) {//single song} reload(songList); } Playback progress bar control Function: Update the playback progress in real time, click the progress bar to adjust the song playback progress // Playback progress is updated in real time audioFile.file.addEventListener('timeupdate', lyricAndProgressMove); // Adjust progress by dragging control.progressDot.addEventListener('click', adjustProgressByDrag); // Adjust progress by clicking control.progressWrap.addEventListener('click', adjustProgressByClick); Playback progress is updated in real time: by modifying the position or width of the corresponding DOM element function lyricAndProgressMove() { const audio = audioFile.file; const controlIndex = control.index; // Initialize song information const songLyricItem = document.getElementsByClassName('song-lyric-item'); if (songLyricItem.length == 0) return; let currentTime = audioFile.currentTime = Math.round(audio.currentTime); let duration = audioFile.duration = Math.round(audio.duration); //Progress bar movement const progressWrapWidth = control.progressWrap.offsetWidth; const currentBarPOS = currentTime / duration * 100; control.progressBar.style.width = `${currentBarPOS.toFixed(2)}%`; const currentDotPOS = Math.round(currentTime / duration * progressWrapWidth); control.progressDot.style.left = `${currentDotPOS}px`; songInfo.currentTimeSpan.innerText = formatTime(currentTime); } Drag to adjust progress: Move the progress bar by dragging, and update the song playback progress synchronously function adjustProgressByDrag() { const fragBox = control.progressDot; const progressWrap = control.progressWrap drag(fragBox, progressWrap) } function drag(fragBox, wrap) { const wrapWidth = wrap.offsetWidth; const wrapLeft = getOffsetLeft(wrap); function dragMove(e) { let disX = e.pageX - wrapLeft; changeProgressBarPos(disX, wrapWidth) } fragBox.addEventListener('mousedown', () => { //Drag operation//Click to enlarge for easy operation fragBox.style.width = `14px`; fragBox.style.height = `14px`; fragBox.style.top = `-7px`; document.addEventListener('mousemove', dragMove); document.addEventListener('mouseup', () => { document.removeEventListener('mousemove', dragMove); fragBox.style.width = `10px`;fragBox.style.height = `10px`;fragBox.style.top = `-4px`; }) }); } function changeProgressBarPos(disX, wrapWidth) { //Progress bar status update const audio = audioFile.file const duration = audioFile.duration let dotPos let barPos if (disX < 0) { dotPos = -4 barPos = 0 audio.currentTime = 0 } else if (disX > 0 && disX < wrapWidth) { dotPos = disX barPos = 100 * (disX / wrapWidth) audio.currentTime = duration * (disX / wrapWidth) } else { dotPos = wrapWidth - 4 barPos = 100 audio.currentTime = duration } control.progressDot.style.left = `${dotPos}px` control.progressBar.style.width = `${barPos}%` } Click the progress bar to adjust: Click the progress bar and update the song playback progress synchronously function adjustProgressByClick(e) { const wrap = control.progressWrap; const wrapWidth = wrap.offsetWidth; const wrapLeft = getOffsetLeft(wrap); const disX = e.pageX - wrapLeft; changeProgressBarPos(disX, wrapWidth) } Lyrics display and highlight Function: Update the lyrics display in real time according to the playback progress, and highlight the current lyrics (by adding styles) // Lyrics display real-time update audioFile.file.addEventListener('timeupdate', lyricAndProgressMove); function lyricAndProgressMove() { const audio = audioFile.file; const controlIndex = control.index; const songLyricItem = document.getElementsByClassName('song-lyric-item'); if (songLyricItem.length == 0) return; let currentTime = audioFile.currentTime = Math.round(audio.currentTime); let duration = audioFile.duration = Math.round(audio.duration); let totalLyricRows = lyric.totalLyricRows = songLyricItem.length; let LyricEle = lyric.ele = songLyricItem[0]; let rowsHeight = lyric.rowsHeight = LyricEle && LyricEle.offsetHeight; //Lyrics movement lrcs[controlIndex].lyric.forEach((item, index) => { if (currentTime === item.time) { lyric.currentRows = index; songLyricItem[index].classList.add('song-lyric-item-active'); index > 0 && songLyricItem[index - 1].classList.remove('song-lyric-item-active'); if (index > 5 && index < totalLyricRows - 5) { songInfo.lyricWrap.scrollTo(0, `${rowsHeight * (index - 5)}`) } } }) } Playback mode settings Function: Click to jump to the play mode and modify the corresponding icon // Play mode setting control.mode.addEventListener('click', changePlayMode); function changePlayMode() { modeControl.index = ++modeControl.index % 3; const mode = control.mode; modeControl.index === 0 ? mode.setAttribute("class", "playerIcon songCycleOrder") : modeControl.index === 1 ? mode.setAttribute("class", "playerIcon songCycleRandom") : mode.setAttribute("class", "playerIcon songCycleOnly") } Project Preview Code address: https://github.com/hcm083214/audio-player This concludes this article about the sample code for implementing a music player with native JS. For more information about JS music player, please search for previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: How to set up a deployment project under Linux system
>>: Super simple qps statistics method (recommended)
Table of contents 1. What is Promise? 2. Why is t...
1. Open the CentOS 7 virtual machine. 2. Log in t...
Triggers can cause other SQL code to run before o...
As shown below: select a1,a2,a1+a2 a,a1*a2 b,a1*1...
Table of contents 1. Basic principles 2. Specific...
MySQL itself does not support recursive syntax, b...
Copy code The code is as follows: <html xmlns=...
Install Nginx First pull the centos image docker ...
view: When a temporary table is used repeatedly, ...
1. Confirm whether MySQL has been installed. You ...
Under Ubuntu 18.04 1. sudo apt install python ins...
mysql5.6.28 installation and configuration method...
Recently, when I was working on my "Football...
The performance of your website or service depend...
<br /> When we browse certain websites and s...