DEV Community

Cover image for How to build a music player with HTML, CSS and javascript
Themba🇿🇦
Themba🇿🇦

Posted on • Updated on

How to build a music player with HTML, CSS and javascript

In this tutorial I will show you how to build a simple music player which you can add to your portfolio. This is a great project to build if you are a beginner in web development because it will show how to use event listeners in javascript. Let’s get started.

Step 1: Setup

So for this project I will be using vscode. It is the best IDE for web development because when you are doing web development you are working with more than one coding language and so vscode is the best because it accommodates all the languages and you can install extensions to help you code.

Our first step is to create the folder for our project. You will open your vscode and you will go to the menu bar at the top, click terminal then click new terminal which will open your terminal at the bottom. Inside your terminal you will run this command to create a new folder, I’m going to call mine musicplayer

mkdir musicplayer
Enter fullscreen mode Exit fullscreen mode

After that we are going to go into the new folder by running this command

cd musicplayer
Enter fullscreen mode Exit fullscreen mode

Inside the folder we going to create 3 more folders

mkdir css js songs
Enter fullscreen mode Exit fullscreen mode

And lastly we going to create 3 new files in different folders.

touch index.html css/style.css js/main.js
Enter fullscreen mode Exit fullscreen mode

Step 2: Adding the structure

Inside your index.html file you are going to add the structure to our application.

TIP: If you are using vscode there is an extension called html5-boilerplate that you can install. This extension helps to build a basic html boilerplate code so you don’t have to code the obvious stuff

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]>      <html class="no-js"> <!--<![endif]-->
<html>
  <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <title></title>
     <meta name="description" content="">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="">
  </head>
  <body>
     <!--[if lt IE 7]>
        <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
     <![endif]-->

     <script src="" async defer></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Inside your body you will create a div with id of main and class of container. Inside of that you will create more divs for the different parts of our music player.


<div id="main" class="container">
        <div id="visuals"></div>
        <div id="metadetails">
           <div id="details">

              <div id="detail-text">
                 <h1 id="song-name">Name Of Song</h1>
                 <p id="artist-name">Artist name</p>
              </div>
           </div>
           <div id="div-slider">
              <span id="timeplayed">00:00</span>
              <div id="greyslider">
                 <div id="fillbar"></div>
                 <div draggable="true" id="slider-nob"></div>
              </div>
              <span id="duration">04:56</span>
           </div>
        </div>
        <div id="controls">
           <button id="previous" onclick="prevSong()">
              <i class="fas fa-step-backward"></i>
           </button>
           <button id="play">
              <i class="fas fa-solid fa-play"></i>
           </button>
           <button id="next" onclick="nextSong()">
              <i class="fas fa-step-forward"></i>
           </button>
        </div>
     </div>

Enter fullscreen mode Exit fullscreen mode

Next you will move to your style.css file in your css folder but before that you will link your css file and js file to your html page, so inside your head tag will add this link:

<link rel="stylesheet" href="css/style.css">
Enter fullscreen mode Exit fullscreen mode

And also

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.css" rel="stylesheet">
Enter fullscreen mode Exit fullscreen mode

The link above is a style link to the fontawesome CDN, this will help in adding icons without having to download and store them inside a img folder.

Step 3: CSS - add some style

At this point all you have is a bare bone html page so you going to add some style your page by going into your style.css file and styling each tag

body {
  font-family: Arial, Helvetica, sans-serif;
  color: #ffffff;
  padding: 0;
  margin: 0;
}

#main {
  width: 100%;
  height: 100vh;
  display: grid;
  grid-template-rows: 60% 1fr 15%;
  background-image: linear-gradient(blue, #000);
}

#metadetails {
  padding: 2%;
}

#details {
  display: flex;
}

#details div {
  margin: 0 2%;
}

#detail-text h1, #detail-text p {
  margin: 0;
}

#controls {
  display: flex;
  place-items: center;
  justify-content: center;
}

button {
  background: none;
  border: none;
  font-size: larger;
  color: grey;
}

#play {
  background-color: #ffffff;
  border-radius: 50rem;
  font-size: x-large;
  color: #000;
  margin: 2%;
  width: 60px;
  height: 60px;
}

#div-slider {
  padding: 1%;
  display: flex;
  place-items: center;
  justify-content: center;
}

#greyslider {
  display: flex;
  position: relative;
  width: 100%;
  height: 5px;
  margin: 1%;
  background-color: grey;
}

#fillbar {
  background-color: #ffffff;
  width: 0;
  height: 100%;
}

#slider-nob {
  position: absolute;
  background-color: #ffffff;
  border-radius: 50%;
  width: 15px;
  height: 15px;
  transform: translate(0, -5px);
}

Enter fullscreen mode Exit fullscreen mode

Step 4: JS - time to bring it to life

Now the fun begins, you going to open your main.js file and here we going to add all the javascript that will make the music player dynamic. You going to be using alot of event listeners here. The thing with event listeners is that there is couple of ways you can write an event listener but for this project we gong to use the old school way which is object.addEventListener(“event”, function).

If you new to web development let me take a moment to explain what an event listener is:
An event listener is as the name implies, it’s a piece of code that listens for events. What are are events? Events are actions that happen inside the DOM, every action is an event, when you move your mouse, when you swipe your finger on the screen, when you click, drag, hover, any action that happens inside a webpage is an event and we can listen to these events so that when that event happens we can can run a particular piece of code, for instance; if we want to play an audio when the play button is clicked, we will create an event listener for the button which will be activated when the button is clicked and then run code which is embedded inside the event listener.

To begin you will declare several variables inside of our js file which we will use.

let current_song = 0;
let audio = null;
let duration = 0;
let playing = false;
let play_pause_btn = document.getElementById("play");
let grey_slider = document.getElementById("greyslider");
let fillbar = document.getElementById("fillbar");
let audio_slider = document.getElementById("slider");
let slider_nob = document.getElementById("slider-nob");
let currentPos, newPos, startPos = 0;
Enter fullscreen mode Exit fullscreen mode

Next since this is a simple music player, you will have to hardcode your objects. In this case your objects will be your music. So you're going to create an array with objects of the different songs.

let songs = [
  {
     song_name: "One More Time",
     artist: "Daft Punk",
     url: "/songs/One more time.mp3",
  },
  {
     song_name: "Otis",
     artist: "Jay Z and Kanye West",
     url: "/songs/04 Otis.mp3",
  },
  {
     song_name: "Lost One",
     artist: "Jay-Z",
     url: "/songs/05 Lost One.mp3",
  },
  {
     song_name: "U don't know",
     artist: "Jay-z",
     url: "/songs/06 U Don't Know.mp3",
  },
  {
     song_name: "Threat",
     artist: "Jay-Z",
     url: "/songs/07 Threat.mp3"
  }
];

Enter fullscreen mode Exit fullscreen mode

As you can see from the url, I have saved all my songs inside the songs folder, so you can put all your music in there.

Next you need to figure out which functions your music player will need, The process i use to come up with my functions is I ask myself first what can the user do on my page, for this project the user can;

  • Play a song
  • Pause a song
  • Skip to the next song
  • Skip to the previous song
  • Skip to a particular part of a song

Next ask yourself what does the system need to do so the program works properly;

  • Set a song
  • Display duration of the song
  • Display the name and artist of the song
  • Move the seeker

By doing this simple exercise you have come up with the basic functions you will need to get started, this process will help keep your code neat and organised. Obviously you will not have everything figured out on your first try of this exercise cause there is always something in code that you have not thought of in your planning phase.

For this project you will use a Javascript constructor called Audio. This is a built in javascript library that will help you play audio. You will start by creating a function that will help set the song

function setSong(index) {
  audio = new Audio(songs[index].url);
  audio.addEventListener("loadeddata", () => {
     audio.controls = true;
     duration = audio.duration;
     document.getElementById("song-name").innerHTML = songs[index].song_name;
     document.getElementById("artist-name").innerHTML = songs[index].artist;
     document.getElementById("duration").innerHTML = convertTime(duration);
  })

  // Listen for when the song ends
  audio.addEventListener("ended", () => {
     nextSong();
  })
}
Enter fullscreen mode Exit fullscreen mode

Next you will create functions for when the user wants to skip to the next or previous song.

function nextSong() {
  audio.pause();
  if(current_song + 1 == songs.length) {
     current_song = 0;
  }else {
     current_song++;
  }
  setSong(current_song);

  // if it was playing then automatically play the next song
  if(playing) {
     audio.play();
     setSeeker();
  } else {
     fillbar.style.width = 0;
     slider_nob.style.left = 0;
  }
}

function prevSong() {
  audio.pause();

  if(current_song == 0) {
     current_song = songs.length - 1;
  }else {
     current_song--;
  }
  setSong(current_song);

  // if it was playing then automatically play the next song
  if(playing) {
     audio.play();
     setSeeker();
  } else {
     fillbar.style.width = 0;
     slider_nob.style.left = 0;
  }

}
Enter fullscreen mode Exit fullscreen mode

Next you will create a function to update the seeker.

function updateSeeker() {
  document.getElementById("timeplayed").innerHTML = convertTime(audio.currentTime);
  let percentage = (audio.currentTime / duration * 100).toFixed(1);
  fillbar.style.width = percentage + "%";
  slider_nob.style.left = (audio.currentTime/ duration * grey_slider.clientWidth).toFixed(1) + "px";
}
Enter fullscreen mode Exit fullscreen mode
function updateSeeker() {
  document.getElementById("timeplayed").innerHTML = convertTime(audio.currentTime);
  let percentage = (audio.currentTime / duration * 100).toFixed(1);
  fillbar.style.width = percentage + "%";
  slider_nob.style.left = (audio.currentTime/ duration * grey_slider.clientWidth).toFixed(1) + "px";
}

function setSeeker() {
  audio.addEventListener("timeupdate", updateSeeker);
}







// Convert time to minutes and seconds so you can dislplay on page
function convertTime(time) {
  // time is already in seconds so there is no need to calculate secinds
  let secs = Math.floor(time);
  let mins = Math.floor(secs / 60);

  secs = secs % 60;
  mins = mins % 60;

  return mins.toString().padStart(2, '0') + ":" + secs.toString().padStart(2, '0')
}



// This function tracks the seeker
function moveObj(e) {
  // calculate the new position
  newPos = startPos - e.clientX;

  // with each move we also want to update the start X and Y
  startPos = e.clientX;

  // set the element's new position:
  if ((slider_nob.offsetLeft - newPos) >= 0 && (slider_nob.offsetLeft - newPos) <= grey_slider.clientWidth - slider_nob.clientWidth) {

     slider_nob.style.left = (slider_nob.offsetLeft - newPos) + "px";
     let percentage = ((slider_nob.offsetLeft - newPos) / (grey_slider.clientWidth - slider_nob.clientWidth) * 100).toFixed(1);
     fillbar.style.width = percentage + "%";

     audio.currentTime = (percentage / 100) * duration;

   }
}

Enter fullscreen mode Exit fullscreen mode

After creating all the functions we need for our program, you are going to add the event listeners which will bring the application to life. The event listeners will listen for any actions that occur in the application and run the function attached to it.

play_pause_btn.addEventListener("click", () => {
  if(!playing) {
     audio.play();
     play_pause_btn.innerHTML = '<i class="fas fa-solid fa-pause"></i>';
     playing = true;
  } else {
     audio.pause();
     play_pause_btn.innerHTML = '<i class="fas fa-solid fa-play"></i>';
     playing = false;
  }
  setSeeker();
})






// mousedown event occurs when a user presses the mouse button on an event
slider_nob.addEventListener("mousedown", (e) => {
  e.preventDefault();
  audio.removeEventListener("timeupdate", updateSeeker);

  // Get the starting position of the cursor
  startPos = e.clientX;

  // mousemove event occurs when a user moves their mouse
  document.addEventListener("mousemove", moveObj);

  // mouseup occurs when a user releases the mouse button
  document.addEventListener("mouseup", () => {
     document.removeEventListener("mousemove", moveObj);
     audio.addEventListener("timeupdate", updateSeeker);
  })
})


setSong(current_song);

Enter fullscreen mode Exit fullscreen mode

So we just created a simple music player with html, css and javascript and you got an introduction to event listeners. Next time we will take this project to the next level by adding a database with MYSQL so you do not have to hardcode your songs in javascript so stay tuned for part 2 of the music player.

You can also follow me on twitter here

Top comments (1)

Collapse
 
xmohammedawad profile image
Mohammed Awad

keep going my man!