Sample code for implementing music player with native JS

Sample code for implementing music player with native JS

This article mainly introduces the sample code of the native JS music player, which is shared with you as follows:

Rendering

Music Player

  • Playback Controls
  • Playback progress bar control
  • Lyrics display and highlight
  • Playback mode settings

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
API used for audio: audio.play() and audio.pause() and audio ended events

// 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
API used for audio: audio timeupdate event, audio.currentTime

// 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)
API used for audio: audio timeupdate event, audio.currentTime

// 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
API used for audio: None

// 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:
  • Native JS music player
  • js+audio to realize music player
  • js to implement a simple music player
  • JavaScript to implement a simple music player
  • Native JS to implement a small music player
  • Sample code for making a simple music player using js
  • JS+html5 to create a simple music player
  • Use js to teach you how to easily create an HTML music player
  • JavaScript to achieve music player with playlist example sharing
  • JS simulates the shrinking, folding and closing effect code of Kugou music player

<<:  How to set up a deployment project under Linux system

>>:  Super simple qps statistics method (recommended)

Recommend

Linux Operation and Maintenance Basic System Disk Management Tutorial

1. Disk partition: 2. fdisk partition If the disk...

MySQL 8.0.18 installation and configuration method graphic tutorial

This article records the installation and configu...

How to set the position of the block element in the middle of the window

How to set the position of the block element in t...

Docker Stack deployment method steps for web cluster

Docker is becoming more and more mature and its f...

What does href=# mean in a link?

Links to the current page. ------------------- Com...

A small question about the execution order of SQL in MySQL

I encountered a sql problem at work today, about ...

vue+element-ui implements the head navigation bar component

This article shares the specific code of vue+elem...

Memcached method for building cache server

Preface Many web applications store data in a rel...

How to modify mysql to allow remote connections

Regarding the issue of MySQL remote connection, w...

Stop using absolute equality operators everywhere in JS

Table of contents Overview 1. Test for null value...

Summary of using the exclamation mark command (!) in Linux

Preface Recently, our company has configured mbp,...

CSS implements six adaptive two-column layout methods

HTML structure <body> <div class="w...