Bài viết mình chia sẻ cho bạn các thêm tiện ích trình phát nhạc sử dụng JavaScript cho website hoặc blog của bạn. Tiện ích này sẽ sử dụng HTML CSS JS.


Tiện ích trình phát nhạc sử dụng JavaScript này có các chức năng phát lặp bài nhạc, phát lặp danh sách nhạc, phát ngẫu nhiên các bài nhạc trong danh sách và các nút play/pause, bài trước bài sau. Bạn cũng có thể xem được danh sách các bài nhạc và bài nhạc đang phát hiện tại trong danh sách.

Chia sẻ code hiển thị trình phát nhạc sử dụng JavaScript

Bước 1: Bạn thêm đoạn code HTML sau vào vị trí bạn muốn hiển thị trình phát nhạc.
<div class='music-box'>
    <div class='top-bar'>
        <i class='has-svg-icon music-more-icons'></i>
        <span>Now Playing</span>
        <i class='has-svg-icon music-horiz-icons'></i>
    </div>
    <div class='img-area'>
        <img alt='' loading='lazy' src='' title='' />
    </div>
    <div class='song-details'>
        <p class='name'></p>
        <p class='artist'></p>
    </div>
    <div class='progress-area'>
        <div class='progress-bar'>
            <audio id='main-audio' src=''></audio>
        </div>
        <div class='song-timer'>
            <span class='current-time'>0:00</span>
            <span class='max-duration'>0:00</span>
        </div>
    </div>
    <div class='controls'>
        <i class='has-svg-icon music-repeat-icons' id='repeat-plist' title='Playlist looped'><span>repeat</span></i>
        <i class='has-svg-icon music-skippre-icons' id='prev'></i>
        <div class='play-pause'>
            <i class='has-svg-icon music-play-icons play'></i>
        </div>
        <i class='has-svg-icon music-skipnext-icons' id='next'></i>
        <i class='has-svg-icon music-queue-icons' id='more-music'></i>
    </div>
    <div class='slider_volumn'>
        <i class='has-svg-icon icon-volume-down' id='min-volume'></i>
        <input class='volume_slider' max='100' min='1' onchange='setVolume()' type='range' value='100' />
        <i class='has-svg-icon icon-volume-up' id='max-volume'></i>
    </div>
    <div class='music-list'>
        <div class='header-music'>
            <div class='row-music'>
                <i class='has-svg-icon list music-queuemenu-icons'></i>
                <span>Music list</span>
            </div>
            <i class='has-svg-icon music-close-icons' id='close'></i>
        </div>
        <ul>
        </ul>
    </div>
</div>
Bước 2: Thêm đoạn CSS sau vào giao diện hoặc là file CSS của bạn. Lưu ý bạn nhớ chỉnh sửa lại CSS cho phù hợp với website hay blog của bạn nhé.
.music-box{width:100%;padding:10px;overflow:hidden;position:relative;background:#fff;box-shadow:0 6px 15px 0 12px 25px 0 rgb(30 30 30 / 4%)}
.music-box i{cursor:pointer}
.top-bar,.progress-area .song-timer,.music-list .header-music,.music-list ul li{display:flex;align-items:center;justify-content:space-between}
.controls{display:flex;align-items:center;justify-content:space-evenly}
.top-bar span{font-size:16px;margin-left:-3px;color:#555}
.img-area{width:185px;height:185px;position:relative;overflow:hidden;margin:15px auto 0;border:5px solid #fff;border-radius:50%;box-shadow:0 6px 12px rgba(0,0,0,0.09)}
.img-area:before{content:'';position:absolute;top:50%;left:50%;width:20px;height:20px;transform:translate(-50%, -50%);background-color:#d6dee7;border-radius:50%;box-shadow:inset 0 0 0 2px #fff;z-index:2}
.img-area img{width:100%;height:100%;border-radius:50%;object-fit:cover}
.music-box.paused .img-area img{animation: rotateAlbumArt 3s linear 0s infinite forwards}
.song-details{text-align:center;margin:20px 0}
.song-details p{color:#666}
.song-details .name{font-size:16px}
.song-details .artist{font-size:13px;opacity:.9;line-height:35px}
.progress-area{height:10px;width:100%;border-radius:50px;background:#f0f0f0;cursor:pointer}
.progress-area .progress-bar{height:inherit;width:0;position:relative;border-radius:inherit;background:linear-gradient(90deg,#7577a9 0%,#66689c 100%)}
.progress-area .song-timer{margin-top:5px}
.song-timer span{font-size:13px;color:#666}
.controls{margin:30px 0 20px}
.controls .play-pause{height:30px;width:30px;display:flex;cursor:pointer;align-items:center;justify-content:center;border-radius:50%;background:#fff}
.play-pause::before{position:absolute;content:"";height:30px;width:30px;border-radius:inherit;background:linear-gradient(#7577a9 0%,#66689c 100%)}
.play-pause i{position:absolute}
.music-list{position:absolute;background:#fff;width:100%;left:0;bottom:-55%;opacity:0;pointer-events:none;z-index:5;padding:15px 30px;box-shadow:0 -5px 10px rgba(0,0,0,0.05);transition:all .15s ease-out}
#repeat-plist > span{display:none}
.music-list.show{bottom:0;opacity:1;pointer-events:auto}
.header-music .row-music{display:flex;align-items:center;font-size:19px}
.header-music .row-music i{cursor:default}
.header-music .row-music span{margin-left:5px;font-size:15px;color:#666666}
.music-list ul{margin:10px 0!important;max-height:260px;overflow:auto}
.music-list ul::-webkit-scrollbar{width:0}
.music-list ul li{list-style:none;display:flex;cursor:pointer;padding-bottom:10px;margin-bottom:10px;color:#666;border-bottom:1px solid #E5E5E5}
.music-list ul li:last-child{border-bottom:0}
.music-list ul li .row span{font-size:15px}
.music-list ul li .row p{opacity:.9;font-size:13px;margin-top:5px}
ul li .audio-duration{font-size:13px}
ul li.playing{pointer-events:none;color:#66689c}
.slider_volumn{display:flex;justify-content:center;align-items:center}
.volume_slider{height:10px;width:100%;border-radius:50px;background:#f0f0f0;cursor:pointer;padding:0;overflow:hidden}
.volume_slider::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:10px;height:10px;background:#66689c;cursor:pointer;border-radius:0 50% 50% 0;box-shadow:-350px 0px 0px 340px #66689c}
@keyframes rotateAlbumArt{0%{ transform: rotateZ(0)}100%{ transform: rotateZ(360deg)}}
Bước 3: Thêm đoạn JavaScript sau vào giao diện hoặc là file JS của bạn. Ở đây mình tạo JS dạng Array để thêm danh sách các bài nhạc.
// Để thêm nhạc bạn sao chép và chỉnh sửa bên trong đoạn array như sau
//   {
//     name: "Tên bài nhạc",
//     artist: "Nghệ sĩ",
//     img: "Tên đường dẫn hình ảnh",
//     src: "Tên đường dẫn theo bài nhạc"
//   }
let allMusic = [
  {
    name: "Harley Bird - Home",
    artist: "Jordan Schor",
    img: "music-1",
    src: "music-1"
  },
  {
    name: "Ikson Anywhere – Ikson",
    artist: "Audio Library",
    img: "music-2",
    src: "music-2"
  },
  {
    name: "Beauz & Jvna - Crazy",
    artist: "Beauz & Jvna",
    img: "music-3",
    src: "music-3"
  },
  {
    name: "Hardwind - Want Me",
    artist: "Mike Archangelo",
    img: "music-4",
    src: "music-4"
  },
  {
    name: "Jim - Sun Goes Down",
    artist: "Jim Yosef x Roy",
    img: "music-5",
    src: "music-5"
  },
  {
    name: "Lost Sky - Vision NCS",
    artist: "NCS Release",
    img: "music-6",
    src: "music-6"
  }
];
Bước cuối: Tiếp tục thêm đoạn JavaScript sau, đoạn JavaScript này là các function và event cho trình phát nhạc.
const wrapper = document.querySelector(".music-box"),
musicImg = wrapper.querySelector(".img-area img"),
musicName = wrapper.querySelector(".song-details .name"),
musicArtist = wrapper.querySelector(".song-details .artist"),
playPauseBtn = wrapper.querySelector(".play-pause"),
prevBtn = wrapper.querySelector("#prev"),
nextBtn = wrapper.querySelector("#next"),
mainAudio = wrapper.querySelector("#main-audio"),
progressArea = wrapper.querySelector(".progress-area"),
progressBar = progressArea.querySelector(".progress-bar"),
musicList = wrapper.querySelector(".music-list"),
moreMusicBtn = wrapper.querySelector("#more-music"),
closemoreMusic = musicList.querySelector("#close"),
volumeslider = wrapper.querySelector(".volume_slider"),
maxvolum = wrapper.querySelector("#max-volume"),
minvolum = wrapper.querySelector("#min-volume");
let musicIndex = Math.floor((Math.random() * allMusic.length) + 1);
isMusicPaused = true;
curr_track = mainAudio;
window.addEventListener("load", ()=>{
  loadMusic(musicIndex);
  playingSong(); 
});
function loadMusic(indexNumb){
  musicName.innerText = allMusic[indexNumb - 1].name;
  musicArtist.innerText = allMusic[indexNumb - 1].artist;
  musicImg.alt = allMusic[indexNumb - 1].artist;
  musicImg.title = allMusic[indexNumb - 1].artist;
  musicImg.src = `https://cdn.jsdelivr.net/gh/ngylduy/storage/image/${allMusic[indexNumb - 1].src}.jpg`;
  // Đây là đường dẫn host lưu ảnh của bạn, ở đây tất cả các tiền tố đều giống nhau khác tên file ảnh như đã nói ở bước 3
  mainAudio.src = `https://ia801400.us.archive.org/27/items/music_20210917/${allMusic[indexNumb - 1].src}.mp3`;
  // Đây là đường dẫn host lưu nhạc của bạn, ở đây tất cả các tiền tố đều giống nhau khác tên file nhạc như đã nói ở bước 3
}
//play music function
function playMusic(){
  wrapper.classList.add("paused");
  playPauseBtn.querySelector("i").classList.remove("music-play-icons");
  playPauseBtn.querySelector("i").classList.add("music-pause-icons");
  mainAudio.play();
}
//pause music function
function pauseMusic(){
  wrapper.classList.remove("paused");
  playPauseBtn.querySelector("i").classList.remove("music-pause-icons");
  playPauseBtn.querySelector("i").classList.add("music-play-icons");
  mainAudio.pause();
}
//prev music function
function prevMusic(){
  musicIndex--; //decrement of musicIndex by 1
  //if musicIndex is less than 1 then musicIndex will be the array length so the last music play
  musicIndex < 1 ? musicIndex = allMusic.length : musicIndex = musicIndex;
  loadMusic(musicIndex);
  playMusic();
  playingSong(); 
}
//next music function
function nextMusic(){
  musicIndex++; //increment of musicIndex by 1
  //if musicIndex is greater than array length then musicIndex will be 1 so the first music play
  musicIndex > allMusic.length ? musicIndex = 1 : musicIndex = musicIndex;
  loadMusic(musicIndex);
  playMusic();
  playingSong(); 
}
// play or pause button event
playPauseBtn.addEventListener("click", ()=>{
  const isMusicPlay = wrapper.classList.contains("paused");
  //if isPlayMusic is true then call pauseMusic else call playMusic
  isMusicPlay ? pauseMusic() : playMusic();
  playingSong();
});
//prev music button event
prevBtn.addEventListener("click", ()=>{
  prevMusic();
});
//next music button event
nextBtn.addEventListener("click", ()=>{
  nextMusic();
});
// update progress bar width according to music current time
mainAudio.addEventListener("timeupdate", (e)=>{
  const currentTime = e.target.currentTime; //getting playing song currentTime
  const duration = e.target.duration; //getting playing song total duration
  let progressWidth = (currentTime / duration) * 100;
  progressBar.style.width = `${progressWidth}%`;
  let musicCurrentTime = wrapper.querySelector(".current-time"),
  musicDuartion = wrapper.querySelector(".max-duration");
  mainAudio.addEventListener("loadeddata", ()=>{
    // update song total duration
    let mainAdDuration = mainAudio.duration;
    let totalMin = Math.floor(mainAdDuration / 60);
    let totalSec = Math.floor(mainAdDuration % 60);
    if(totalSec < 10){ //if sec is less than 10 then add 0 before it
      totalSec = `0${totalSec}`;
    }
    musicDuartion.innerText = `${totalMin}:${totalSec}`;
  });
  // update playing song current time
  let currentMin = Math.floor(currentTime / 60);
  let currentSec = Math.floor(currentTime % 60);
  if(currentSec < 10){ //if sec is less than 10 then add 0 before it
    currentSec = `0${currentSec}`;
  }
  musicCurrentTime.innerText = `${currentMin}:${currentSec}`;
});
// update playing song currentTime on according to the progress bar width
progressArea.addEventListener("click", (e)=>{
  let progressWidth = progressArea.clientWidth; //getting width of progress bar
  let clickedOffsetX = e.offsetX; //getting offset x value
  let songDuration = mainAudio.duration; //getting song total duration
  
  mainAudio.currentTime = (clickedOffsetX / progressWidth) * songDuration;
  playMusic(); //calling playMusic function
  playingSong();
});
//change loop, shuffle, repeat icon onclick
const repeatBtn = wrapper.querySelector("#repeat-plist span");
wrapper.querySelector("#repeat-plist").addEventListener("click", ()=>{
  let getText = repeatBtn.innerText; //getting this tag innerText
  switch(getText){
    case "repeat":
      repeatBtn.innerText = "repeat_one";
      wrapper.querySelector("#repeat-plist").classList.toggle("music-repeat-icons");
      wrapper.querySelector("#repeat-plist").classList.toggle("music-repeatone-icons");
      wrapper.querySelector("#repeat-plist").setAttribute("title", "Song looped");
      break;
    case "repeat_one":
      repeatBtn.innerText = "shuffle";
      wrapper.querySelector("#repeat-plist").classList.toggle("music-repeatone-icons");
      wrapper.querySelector("#repeat-plist").classList.toggle("music-shuffle-icons");
      wrapper.querySelector("#repeat-plist").setAttribute("title", "Playback shuffled");
      break;
    case "shuffle":
      repeatBtn.innerText = "repeat";
      wrapper.querySelector("#repeat-plist").classList.toggle("music-shuffle-icons");
      wrapper.querySelector("#repeat-plist").classList.toggle("music-repeat-icons");
      wrapper.querySelector("#repeat-plist").setAttribute("title", "Playlist looped");
      break;
  }
});
//code for what to do after song ended
mainAudio.addEventListener("ended", ()=>{
  // we'll do according to the icon means if user has set icon to
  // loop song then we'll repeat the current song and will do accordingly
  let getText = repeatBtn.innerText; //getting this tag innerText
  switch(getText){
    case "repeat":
      nextMusic(); //calling nextMusic function
      break;
    case "repeat_one":
      mainAudio.currentTime = 0; //setting audio current time to 0
      loadMusic(musicIndex); //calling loadMusic function with argument, in the argument there is a index of current song
      playMusic(); //calling playMusic function
      break;
    case "shuffle":
      let randIndex = Math.floor((Math.random() * allMusic.length) + 1); //genereting random index/numb with max range of array length
      do{
        randIndex = Math.floor((Math.random() * allMusic.length) + 1);
      }while(musicIndex == randIndex); //this loop run until the next random number won't be the same of current musicIndex
      musicIndex = randIndex; //passing randomIndex to musicIndex
      loadMusic(musicIndex);
      playMusic();
      playingSong();
      break;
  }
});
//show music list onclick of music icon
moreMusicBtn.addEventListener("click", ()=>{
  musicList.classList.toggle("show");
});
closemoreMusic.addEventListener("click", ()=>{
  moreMusicBtn.click();
});
const ulTag = wrapper.querySelector("ul");
// let create li tags according to array length for list
for (let i = 0; i < allMusic.length; i++) {
  //let's pass the song name, artist from the array
  let liTag = `<li li-index="${i + 1}">
                <div class="row">
                  <span>${allMusic[i].name}</span>
                  <p>${allMusic[i].artist}</p>
                </div>
                <span id="${allMusic[i].src}" class="audio-duration">3:40</span>
                <audio class="${allMusic[i].src}" src="https://cdn.jsdelivr.net/gh/ngylduy/storage/music/${allMusic[i].src}.mp3"></audio>
              </li>`;
  ulTag.insertAdjacentHTML("beforeend", liTag); //inserting the li inside ul tag
  let liAudioDuartionTag = ulTag.querySelector(`#${allMusic[i].src}`);
  let liAudioTag = ulTag.querySelector(`.${allMusic[i].src}`);
  liAudioTag.addEventListener("loadeddata", ()=>{
    let duration = liAudioTag.duration;
    let totalMin = Math.floor(duration / 60);
    let totalSec = Math.floor(duration % 60);
    if(totalSec < 10){ //if sec is less than 10 then add 0 before it
      totalSec = `0${totalSec}`;
    };
    liAudioDuartionTag.innerText = `${totalMin}:${totalSec}`; //passing total duation of song
    liAudioDuartionTag.setAttribute("t-duration", `${totalMin}:${totalSec}`); //adding t-duration attribute with total duration value
  });
}
//play particular song from the list onclick of li tag
function playingSong(){
  const allLiTag = ulTag.querySelectorAll("li");
  
  for (let j = 0; j < allLiTag.length; j++) {
    let audioTag = allLiTag[j].querySelector(".audio-duration");
    
    if(allLiTag[j].classList.contains("playing")){
      allLiTag[j].classList.remove("playing");
      let adDuration = audioTag.getAttribute("t-duration");
      audioTag.innerText = adDuration;
    }
    //if the li tag index is equal to the musicIndex then add playing class in it
    if(allLiTag[j].getAttribute("li-index") == musicIndex){
      allLiTag[j].classList.add("playing");
      audioTag.innerText = "Playing";
    }
    allLiTag[j].setAttribute("onclick", "clicked(this)");
  }
}
//particular li clicked function
function clicked(element){
  let getLiIndex = element.getAttribute("li-index");
  musicIndex = getLiIndex; //updating current song index with clicked li index
  loadMusic(musicIndex);
  playMusic();
  playingSong();
}
function setVolume() {
  curr_track.volume = volumeslider.value / 100;
}
maxvolum.addEventListener("click", ()=>{
curr_track.volume = 1;
volumeslider.value = 100
})
minvolum.addEventListener("click", ()=>{
curr_track.volume = 0.01;
volumeslider.value = 0
})
Bạn nào không hiểu đoạn nào hay lỗi gì thì cứ comments bên dưới bài viết này mình sẽ hỗ trợ nhé!