HomeJavascript ProjectCreate A Music Player Using Javascript | Javascript Audio Player

Create A Music Player Using Javascript | Javascript Audio Player

Hey friends, today in this blog you’ll learn How to Create A Music Player Using Javascript | Javascript Audio Player. We’ll use HTML CSS and Pure JavaScript to create this awesome music player. I Hope this blog will be helpful.

This project Music Player Using Javascript has many features like you can play and pause a song or play the next or previous song and loop, repeat or shuffle a song. You can view your songs list and also know which song is currently playing and you’ll also select the song from the list to play. I have also created a full video tutorial of this music player, you can watch a video

Video Tutorial of Music Player in JavaScript

Music Player Using Javascript [Source Codes]

To create this project “Music Player Using JavaScript”. First, you need to create 4 four files, HTML File, CSS File, and JavaScript File. After creating these files just Copy the given source code and paste into your text editor and edit it according to your requirement. You can also download the source code of the music player from the given download button.

First you create an HTML file with the name of index.html and paste the given codes in your HTML file and the images and song that are used on this music player , you can download all images and songs it from the download button given below.

# HTML CODE

First, you create an HTML file(index.html) and paste the given codes in your HTML file.

<!-- coding with nick -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Music Player | Coding With Nick</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

</head>

<body>
  <div class="container">

    <div class="top-bar">
      <i class="material-icons">favorite_border</i>
      <span>Now Playing</span>
      <i class="material-icons">add</i>
    </div>
    <div class="img-area">
      <img src="" alt="">
    </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>
      <audio id="main-audio" src=""></audio>
    </div>

    <div class="controls">
      <i id="repeat-plist" class="material-icons" title="Playlist looped">repeat</i>
      <i id="prev" class="material-icons prev">fast_rewind</i>
      <div class="play-pause">
        <i class="material-icons play">play_arrow</i>
      </div>
      <i id="next" class="material-icons next">fast_forward</i>
      <i id="more-music" class="material-icons">queue_music</i>
    </div>

    <div class="music-list">
      <div class="header">
        <div class="row">
          <i class="list material-icons">queue_music</i>
          <span>Music List</span>
        </div>
        <i id="close" class="material-icons">close</i>
      </div>
      <ul>
       
      </ul>
    </div>


  </div>

  <script src="js/music-list.js"></script>
  <script src="js/script.js"></script>

</body>

</html>

# CSS CODE

Second, you create anCSS file(style.css) and paste the given codes in your HTML file.

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
*::before, *::after{
  padding: 0;
  margin: 0;
}

body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: rgb(207, 207, 207);
}
.container{
  width: 350px;
  height: 650px;
  padding: 25px 30px;
  overflow: hidden;
  position: relative;
  border-radius: 15px;
  background: linear-gradient(#9ce3ff 0%, #fd878d 90%);
  box-shadow: 0px 6px 15px rgba(0, 0, 0, 0.342);
   background-blend-mode: screen;
}
.container i{
  cursor: pointer;
}
.top-bar, .progress-area .song-timer, 
.controls, .music-list .header, .music-list ul li{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.top-bar i{
  font-size: 30px;
  color: #ffffff;
}
.top-bar i:first-child{
  margin-left: -7px;
  font-size: 22px;
}
.top-bar span{
  font-size: 18px;
  margin-left: -3px;
  color: #ffffff;
}

.img-area{
  width: 100%;
  height: 280px;
  overflow: hidden;
  margin-top: 25px;
  border-radius: 50%;
  border-radius: 50%;
	box-shadow: 0 0 0 5px #ffffff,
	0 0 2px #fff,
	13px 13px 20px #31313163,
	-10px -10px 20px #e6f6ff;

}
.img-area img{
  width: 100%;
  height: 100%;
  object-fit: cover;
  
}
.song-details{
  text-align: center;
  margin: 30px 0;
}
.song-details p{
  color: #ffffff;
}
.song-details .name{
  font-size: 21px;
}
.song-details .artist{
  font-size: 15px;
  opacity: 0.9;
  line-height: 35px;
}
.progress-area{
  height: 6px;
  width: 100%;
  border-radius: 50px;
  background: #f0f0f081;
  cursor: pointer;
}
.progress-area .progress-bar{
  
  height: inherit;
  width: 0%;
  position: relative;
  border-radius: inherit;
  background: #ffffff;
}
.progress-bar::before{
  content: "";
  position: absolute;
  height: 12px;
  width: 12px;
  border-radius: 50%;
  top: 50%;
  right: -5px;
  z-index: 2;
  opacity: 0;
  pointer-events: none;
  transform: translateY(-50%);
  background: inherit;
  transition: opacity 0.2s ease;
}
.progress-area:hover .progress-bar::before{
  opacity: 1;
  pointer-events: auto;
}
.progress-area .song-timer{
  margin-top: 2px;
}
.song-timer span{
  font-size: 13px;
  color: #ffffff;
}
.controls{
  margin: 70px 0 5px 0;
}
.controls i{
  font-size: 28px;
  user-select: none;
  background:#ffffff;
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.controls i:nth-child(2),
.controls i:nth-child(4){
  font-size: 43px;
}
.controls #prev{
  margin-right: -13px;
}

.controls #next{
  margin-left: -13px;
}

.controls i.prev{
  font-size: 38px;
  }
  .controls i.next{
    font-size: 38px;
    }

.controls .play-pause{
  height: 54px;
  width: 54px;
  display: flex;
  cursor: pointer;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  box-shadow: 
	0 0 2px #fff,
	8px 8px 15px #ff5e66,
	-3px -3px 15px #f0ecec	
	;
 
}
.play-pause::before{
  position: absolute;
  content: "";
  height: 43px;
  width: 43px;
  border-radius: inherit;
  background: transparent;
  border: 3px solid #ffffff;
}
.play-pause i{
  height: 43px;
  width: 43px;
  line-height: 43px;
  text-align: center;
  background: inherit;
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: white;
  position: absolute;
  
}
.prev , .next {
  box-shadow: 
	0 0 2px #fff,
	8px 8px 15px #ff5e66,
	-3px -3px 15px #f0ecec;
  border-radius: 50%;
}
.music-list{
  position: absolute;
  width: 100%;
  bottom: -55%;
  opacity: 0;
  pointer-events: none;
  left: 0;
  box-shadow: 0px -5px 10px rgba(0,0,0,0.1);
  z-index: 5;
  padding: 15px 30px;
  border-radius: 15px;
  background:
  linear-gradient(rgba(255, 255, 255, 0.973), transparent),
  linear-gradient(to top left, rgb(255, 23, 23), transparent),
  linear-gradient(to top right, rgb(0, 183, 255), transparent);
  background-blend-mode: screen;
  transition: all 0.15s ease-in-out;
}
.music-list.show{
  bottom: 0;
  opacity: 1;
  pointer-events: auto;
}
.music-list ul{
  margin-top: 10px 0;
  max-height: 260px;
  overflow: auto;
}
.music-list ul li{
  list-style: none;
  display: flex;
  cursor: pointer;
  padding-bottom: 10px;
  margin-bottom: 5px;
  color: #000000;
  border-bottom:  1px solid #e5e5e5;
}
.music-list ul li:last-child{
  border-bottom: 0px;
}
.music-list ul li .row span{
  font-size: 17px;
}
.music-list ul li .row p{
  opacity: 0.6;
}
ul li .audio-duration{
  font-size: 16px;
}

.header .row{
  display: flex;
  align-items: center;
  font-size: 19px;
  color: #515c6f;
}

.header .row i{
  cursor: default;
}
.header .row span{
  margin-left: 5px;
}
.header #close{
  font-size: 22px;
  color: #515c6f;
}
.music-list ul::-webkit-scrollbar{
  width: 0;
}
.music-list ul li:hover{
  color: #0e9fff;
}
ul li.playing{
  pointer-events: none;
  color: #0e9fff;
}


# JS CODE

Third, you create a JavaScript file (music-list.js) and paste the given codes in your JavaScript file.

let allMusic = [

{
    name: "Harley Bird - Home",
    artist: "Jordan Scho",
    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"
},

];

Last, create a JavaScript file( script.js ) and paste the given codes in your JavaScript file.

// Coding With Nick
// Add Tags And Elements

const container = document.querySelector(".container"),
    musicImg = container.querySelector(".img-area img"),
    musicName = container.querySelector(".song-details .name"),
    musicArtist = container.querySelector(".song-details .artist"),
    mainAudio = container.querySelector("#main-audio"),
    playpauseBtn = container.querySelector(".play-pause"),
    nextBtn = container.querySelector("#next"),
    prevBtn = container.querySelector("#prev"),
    progressArea = container.querySelector(".progress-area"),
    progressBar = container.querySelector(".progress-bar"),
    musicList = container.querySelector(".music-list"),
    moreMusicBtn = container.querySelector("#more-music"),
    closemoreMusic = container.querySelector("#close");



let musicIndex = Math.floor((Math.random() * allMusic.length) + 1);

window.addEventListener("load", () => {
    loadMusic(musicIndex);
    playingSong();
})

// load music function

function loadMusic(indexNumb) {
    musicName.innerText = allMusic[indexNumb - 1].name;
    musicArtist.innerText = allMusic[indexNumb - 1].artist;
    musicImg.src = `images/${allMusic[indexNumb - 1].img}.jpg`;
    mainAudio.src = `songs/${allMusic[indexNumb - 1].src}.mp3`;
}


// play music function
function playMusic() {
    container.classList.add("paused");
    playpauseBtn.querySelector("i").innerText = "pause";
    mainAudio.play();
}

// pause music function
function pauseMusic() {
    container.classList.remove("paused");
    playpauseBtn.querySelector("i").innerText = "play_arrow";
    mainAudio.pause();
}


// 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();
}
// Prev Music function
function prevMusic() {
    musicIndex--; //increment of musicIndex by 1
    // if musicIndex is less than array length then musicIndex will be 1 so the first music play
    musicIndex < 1 ? musicIndex = allMusic.length : musicIndex = musicIndex;
    loadMusic(musicIndex);
    playMusic();
    playingSong();
}


// play or Pause button event
playpauseBtn.addEventListener("click", () => {
    const isMusicPaused = container.classList.contains("paused");

    isMusicPaused ? pauseMusic() : playMusic();

});

// next music button event
nextBtn.addEventListener("click", () => {
    nextMusic();
});


// prev music button event
prevBtn.addEventListener("click", () => {
    prevMusic();
});

// update progressbar 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 total song duration
    let progressWidth = (currentTime / duration) * 100;
    progressBar.style.width = `${progressWidth}%`;



    let musicCurrentTime = container.querySelector(".current-time"),
        musicDuration = container.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}`;
        }

        musicDuration.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 current width onaccording 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();

});

// change loop, shufle, repeat icon onclick
const repeatBtn = container.querySelector("#repeat-plist");
repeatBtn.addEventListener("click", () => {
    let getText = repeatBtn.innerText; //getting this tag innerText
    switch (getText) {
        case "repeat":
            repeatBtn.innerText = "repeat_one";
            repeatBtn.setAttribute("title", "song looped");
            break;
        case "repeat_one":
            repeatBtn.innerText = "shuffle";
            repeatBtn.setAttribute("title", "playback shuffled");
            break;
        case "shuffle":
            repeatBtn.innerText = "repeat";
            repeatBtn.setAttribute("title", "playlist looped");
            break;

    }

});

// above we just change icon, now let's work on what to do after song ended
mainAudio.addEventListener("ended", () => {
    let getText = repeatBtn.innerText; //getting this tag innerText
    switch (getText) {
        case "repeat":
            nextMusic(); //calling nect music function
            break;
        case "repeat_one":
            mainAudio.currentTime = 0; //setting audio current time to 0
            loadMusic(musicIndex); //calling load music 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);
            do {
                randIndex = Math.floor((Math.random() * allMusic.length) + 1);
            } while (musicIndex == randIndex); //thi 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 the music list onclick music icon


moreMusicBtn.addEventListener("click", () => {
    musicList.classList.toggle("show");
});
closemoreMusic.addEventListener("click", () => {
    moreMusicBtn.click();
});


const ulTag = container.querySelector("ul");

// let create li tags according to array lenght for list

for (let i = 0; i < allMusic.length; i++) {
    let liTag = `<li li-index="${i + 1}">
    <div class="row">
      <span>${allMusic[i].name}</span>
      <p>${allMusic[i].artist}</p>
    </div>
    <audio class="${allMusic[i].src} " src="songs/${allMusic[i].src}.mp3"></audio>
    <span id="${allMusic[i].src}" class="audio-duration">1:45</span>
  </li>`;
  ulTag.insertAdjacentHTML("beforeend", liTag);

  let liAudioDurationTag = 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}`;
    }

    liAudioDurationTag.innerText = `${totalMin}:${totalSec}`;
    // adding t-duration attribute with total duration value
    liAudioDurationTag.setAttribute("t-duration", `${totalMin}:${totalSec}`);
  });

}
// play particular song from the list on click of li tag

const allLiTags = ulTag.querySelectorAll("li");
function playingSong() {
    for (let j = 0; j < allLiTags.length; j++) {
   let audioTag = allLiTags[j].querySelector(".audio-duration");
        // let remove playing class from all other li expect the last one which is clicked
        if(allLiTags[j].classList.contains("playing")){
            allLiTags[j].classList.remove("playing");
        //  let's get that audio duration value and pass to .audio-duration innertext
        let adDuration = audioTag.getAttribute("t-duration");
        audioTag.innerText = adDuration;
        }
    
        // if there is an li tag which li index is equal to musicIndex
        // then this music is playing now and we'll style it
    
        if(allLiTags[j].getAttribute("li-index") == musicIndex){
            allLiTags[j].classList.add("playing");
            audioTag.innerText = "Playing";
        }
    
        // adding on click attribute in all li tags
        allLiTags[j].setAttribute("onclick", "clicked(this)");
    }
}

// lets play song on click li 
function clicked(element){

    // getting li index of particular clicked li tag
    let getLiIndex = element.getAttribute("li-index");
    musicIndex =  getLiIndex; //passing that liindex to musicIndex
    loadMusic(musicIndex);
    playMusic(); 
    playingSong();
   
}

That’s all, now you’ve successfully created a Music Player Using JavaScript. If your code doesn’t work or you’ve faced any error And problem’s , please download the source code from the given download button. It’s free and a .zip file will be downloaded then you’ve extract it.



Read More –

How To Create Responsive Image Gallery Using Html & Css

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

- Advertisment -

Categories