Open In App

Create a Music Player using JavaScript

Last Updated : 03 Oct, 2022
Like Article

As streaming is increasingly being adopted by users, online media players have become essential for consuming media on the internet. Music players allow one to enjoy music in any browser and supports a lot of the features of an offline music player.
We will be creating a music player with a clean user interface that can be used to play music in the browser. We will also implement features like seeking and volume control. HTML has several methods in the HTMLMediaElement interface that can be used to play audio files and control its playback without using any other library.
We will start by creating the HTML layout first that defines the structure of the player, make it look good by styling using CSS and then write the player logic for all the functions in JavaScript.

The HTML Layout 
The HTML layout defines the element structure that would be shown on the page. The player can be divided into the following portions:

  • Details Portion: This section shows the details of the current track being played. It includes the track number, track album, track name and track artist.
  • Buttons Portion: This section shows the buttons that are used to control the playback of the track. It includes the play/pause button, the previous and next track buttons. They would have an onclick() method that calls a specific function defined in the JavaScript file.
  • Sliders Portion: This section contains the seek slider and volume slider that can be used to control the playback and volume.

We will be using FontAwesome icons to get the icons for all the buttons used on the page. The custom CSS and JavaScript we will write later is also linked in the file.
The HTML code is as follows: 


<!DOCTYPE html>
<html lang="en">
  <title>Simple Music Player</title>
  <!-- Load FontAwesome icons -->
  <link rel="stylesheet"
  <!-- Load the custom CSS style file -->
  <link rel="stylesheet" type="text/css" href="style.css">
  <div class="player">
    <!-- Define the section for displaying details -->
    <div class="details">
      <div class="now-playing">PLAYING x OF y</div>
      <div class="track-art"></div>
      <div class="track-name">Track Name</div>
      <div class="track-artist">Track Artist</div>
    <!-- Define the section for displaying track buttons -->
    <div class="buttons">
      <div class="prev-track" onclick="prevTrack()">
        <i class="fa fa-step-backward fa-2x"></i>
      <div class="playpause-track" onclick="playpauseTrack()">
        <i class="fa fa-play-circle fa-5x"></i>
      <div class="next-track" onclick="nextTrack()">
        <i class="fa fa-step-forward fa-2x"></i>
    <!-- Define the section for displaying the seek slider-->
    <div class="slider_container">
      <div class="current-time">00:00</div>
      <input type="range" min="1" max="100"
        value="0" class="seek_slider" onchange="seekTo()">
      <div class="total-duration">00:00</div>
    <!-- Define the section for displaying the volume slider-->
    <div class="slider_container">
      <i class="fa fa-volume-down"></i>
      <input type="range" min="1" max="100"
        value="99" class="volume_slider" onchange="setVolume()">
      <i class="fa fa-volume-up"></i>
  <!-- Load the main script for the player -->
  <script src="main.js"></script>

The CSS Styling 
Using CSS we can style the different portions to make it more visually appealing: 

  • The flex layout is used to arrange the various elements of the player and align them to the middle of the page.
  • The track art image is given a fixed dimension and made rounded using the border-radius property.
  • The two sliders have been modified from their default look by using the appearance property. The height and background are changed to suit the color scheme. They are also given slight transparency that smoothly transitions to the full opacity using the transition property.
  • All the playback controls have their cursor property set so that it changes to a pointer whenever the mouse hovers over it.



body {
  background-color: lightgreen;
  /* Smoothly transition the background color */
  transition: background-color .5s;
/* Using flex with the column direction to
   align items in a vertical direction */
.player {
  height: 95vh;
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
.details {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  margin-top: 25px;
.track-art {
  margin: 25px;
  height: 250px;
  width: 250px;
  background-image: URL(
  background-size: cover;
  background-position: center;
  border-radius: 15%;
/* Changing the font sizes to suitable ones */
.now-playing {
  font-size: 1rem;
.track-name {
  font-size: 3rem;
.track-artist {
  font-size: 1.5rem;
/* Using flex with the row direction to
   align items in a horizontal direction */
.buttons {
  display: flex;
  flex-direction: row;
  align-items: center;
.next-track {
  padding: 25px;
  opacity: 0.8;
  /* Smoothly transition the opacity */
  transition: opacity .2s;
/* Change the opacity when mouse is hovered */
.next-track:hover {
  opacity: 1.0;
/* Define the slider width so that it scales properly */
.slider_container {
  width: 75%;
  max-width: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
/* Modify the appearance of the slider */
.seek_slider, .volume_slider {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  height: 5px;
  background: black;
  opacity: 0.7;
  -webkit-transition: .2s;
  transition: opacity .2s;
/* Modify the appearance of the slider thumb */
.volume_slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  width: 15px;
  height: 15px;
  background: white;
  cursor: pointer;
  border-radius: 50%;
/* Change the opacity when mouse is hovered */
.volume_slider:hover {
  opacity: 1.0;
.seek_slider {
  width: 60%;
.volume_slider {
  width: 30%;
.total-duration {
  padding: 10px;
i.fa-volume-up {
  padding: 10px;
/* Change the mouse cursor to a pointer
   when hovered over */
i.fa-step-backward {
  cursor: pointer;

The result of the HTML layout and CSS styling would give the following appearance:


JavaScript logic of the player:
The logic of the player is defined in the JavaScript file. There are several functions that work together to handle all the functions of the player.
Step 1: Defining all the variables and accessing the HTML elements 
The required elements in the HTML layout that are to be dynamically changed are first selected using the querySelector() method. They are then assigned variable names so that they could be accessed and modified. Other variables that would be accessed throughout the program are also defined.


// Select all the elements in the HTML page
// and assign them to a variable
let now_playing = document.querySelector(".now-playing");
let track_art = document.querySelector(".track-art");
let track_name = document.querySelector(".track-name");
let track_artist = document.querySelector(".track-artist");
let playpause_btn = document.querySelector(".playpause-track");
let next_btn = document.querySelector(".next-track");
let prev_btn = document.querySelector(".prev-track");
let seek_slider = document.querySelector(".seek_slider");
let volume_slider = document.querySelector(".volume_slider");
let curr_time = document.querySelector(".current-time");
let total_duration = document.querySelector(".total-duration");
// Specify globally used values
let track_index = 0;
let isPlaying = false;
let updateTimer;
// Create the audio element for the player
let curr_track = document.createElement('audio');
// Define the list of tracks that have to be played
let track_list = [
    name: "Night Owl",
    artist: "Broke For Free",
    image: "Image URL",
    path: "Night_Owl.mp3"
    name: "Enthusiast",
    artist: "Tours",
    image: "Image URL",
    path: "Enthusiast.mp3"
    name: "Shipping Lanes",
    artist: "Chad Crouch",
    image: "Image URL",
    path: "Shipping_Lanes.mp3",

Step 2: Loading a new track from the tracklist 
All the tracks that have to be played are defined in the tracklist as objects. These objects contain properties like the name, artist, image and path to the track. Each of the tracks can then be accessed using its track index.
To load a track, a function loadTrack() is defined which handles the following things: 

  • Reset all the values of the previous track 
    A resetValues() function is created which handles the resetting of the duration value and the slider to their initial values before a new track starts. This prevents the jumping of the seek slider while the new track loads.
  • Loading the track 
    The audio element is assigned a new source using its src property. It may be given any path from the filesystem or a URL. The load() method is then used on the audio element to get the track ready.
  • Updating the track art to be shown 
    The track art is fetched from the array and assigned with the help of the backgroundImage property.
  • Updating the track details to be shown 
    The track details are fetched from the array and assigned with the help of the textContent property.
  • Adding event listeners to the track 
    The media element has two event listeners added to it, the first one to update the current seek position and the second one to load the next track when the current track finishes.
  • Setting a random colored background 
    A coloured background is generated by randomising the red, green and blue values used and setting it as a color. The effect is animated by using the transition property on the background-color.


function loadTrack(track_index) {
  // Clear the previous seek timer
  // Load a new track
  curr_track.src = track_list[track_index].path;
  // Update details of the track =
     "url(" + track_list[track_index].image + ")";
  track_name.textContent = track_list[track_index].name;
  track_artist.textContent = track_list[track_index].artist;
  now_playing.textContent =
     "PLAYING " + (track_index + 1) + " OF " + track_list.length;
  // Set an interval of 1000 milliseconds
  // for updating the seek slider
  updateTimer = setInterval(seekUpdate, 1000);
  // Move to the next track if the current finishes playing
  // using the 'ended' event
  curr_track.addEventListener("ended", nextTrack);
  // Apply a random background color
function random_bg_color() {
  // Get a random number between 64 to 256
  // (for getting lighter colors)
  let red = Math.floor(Math.random() * 256) + 64;
  let green = Math.floor(Math.random() * 256) + 64;
  let blue = Math.floor(Math.random() * 256) + 64;
  // Construct a color with the given values
  let bgColor = "rgb(" + red + ", " + green + ", " + blue + ")";
  // Set the background to the new color = bgColor;
// Function to reset all values to their default
function resetValues() {
  curr_time.textContent = "00:00";
  total_duration.textContent = "00:00";
  seek_slider.value = 0;

Step 3: Configuring the player buttons 
A function playTrack() handles the playing of the currently loaded track. The play() method of the HTMLMediaElement API is used for this function. The icon of the button also changes to the pause icon. This is done by using one of the icons from the FontAwesome library and inserting it using innerHTML.
A function pauseTrack() handles the playing of the currently loaded track. The pause() method of the HTMLMediaElement API is used for this function. The icon of the button also changes back to the play icon. This is done by using one of the icons from the FontAwesome library and inserting it using innerHTML.
These two functions are invoked depending on whether the track is currently playing or not. The playpause() function handles the actual play/pause control of the track. 
A function prevTrack() handles the loading of the previous track and moving the index backward. The index is reset to the last track when the index reaches the first track. The loadTrack() method defined above is used for loading the new track.
Similarly, a function nextTrack() handles the loading of the next track and moving the index forward. The index is reset to the first track when the index reaches the last track. The loadTrack() method defined above is used for loading the new track.


function playpauseTrack() {
  // Switch between playing and pausing
  // depending on the current state
  if (!isPlaying) playTrack();
  else pauseTrack();
function playTrack() {
  // Play the loaded track;
  isPlaying = true;
  // Replace icon with the pause icon
  playpause_btn.innerHTML = '<i class="fa fa-pause-circle fa-5x"></i>';
function pauseTrack() {
  // Pause the loaded track
  isPlaying = false;
  // Replace icon with the play icon
  playpause_btn.innerHTML = '<i class="fa fa-play-circle fa-5x"></i>';
function nextTrack() {
  // Go back to the first track if the
  // current one is the last in the track list
  if (track_index < track_list.length - 1)
    track_index += 1;
  else track_index = 0;
  // Load and play the new track
function prevTrack() {
  // Go back to the last track if the
  // current one is the first in the track list
  if (track_index > 0)
    track_index -= 1;
  else track_index = track_list.length - 1;
  // Load and play the new track

Step 4: Configuring the sliders portion
We will be setting up two sliders that control the seek slider and the volume slider.

  • The seek slider 
    The seek slider shows the current playback position on a slider by updating it with the current time of the track. A new function is created seekUpdate() which handles the updating of the seek slider relative to the current time of the track. The seek slider position is calculated and set using the value property. 
    Now, this function has to be called every time the track progresses further. This can be done by scheduling it to be updated every second. This can be done using the setInterval() method with an interval of 1000 milliseconds. This timer is cleared every time a new track is loaded.
    This function also handles the changing of the time elapsed and the total duration of the track, which is updated every time this function fires. The minutes and the seconds are separately calculated and properly formatted to be displayed. 
  • The volume slider 
    The volume slider is used to display an set the current volume of the track. A new function is created setVolume() which handles the setting of the volume slider whenever the user changes it. 


function seekTo() {
  // Calculate the seek position by the
  // percentage of the seek slider
  // and get the relative duration to the track
  seekto = curr_track.duration * (seek_slider.value / 100);
  // Set the current track position to the calculated seek position
  curr_track.currentTime = seekto;
function setVolume() {
  // Set the volume according to the
  // percentage of the volume slider set
  curr_track.volume = volume_slider.value / 100;
function seekUpdate() {
  let seekPosition = 0;
  // Check if the current track duration is a legible number
  if (!isNaN(curr_track.duration)) {
    seekPosition = curr_track.currentTime * (100 / curr_track.duration);
    seek_slider.value = seekPosition;
    // Calculate the time left and the total duration
    let currentMinutes = Math.floor(curr_track.currentTime / 60);
    let currentSeconds = Math.floor(curr_track.currentTime - currentMinutes * 60);
    let durationMinutes = Math.floor(curr_track.duration / 60);
    let durationSeconds = Math.floor(curr_track.duration - durationMinutes * 60);
    // Add a zero to the single digit time values
    if (currentSeconds < 10) { currentSeconds = "0" + currentSeconds; }
    if (durationSeconds < 10) { durationSeconds = "0" + durationSeconds; }
    if (currentMinutes < 10) { currentMinutes = "0" + currentMinutes; }
    if (durationMinutes < 10) { durationMinutes = "0" + durationMinutes; }
    // Display the updated duration
    curr_time.textContent = currentMinutes + ":" + currentSeconds;
    total_duration.textContent = durationMinutes + ":" + durationSeconds;

Step 5: Starting the player
The first track is loaded by calling the loadTrack() function. This will load the first track from the tracklist and update all the details of the track. The user can then start playing the track using the play button. The previous and next track button would load the previous and next track respectively and start playing them.
The next track is automatically loaded when a track finishes playing. The user can seek to a position in the track using the seek slider. The volume can also be adjusted using the volume slider.


// Load the first track in the tracklist

Final Demonstration
The player is now ready to be used in any browser. New tracks can be added to the tracklist to play the music of your choice.

Try Online:
Source Code:

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

Similar Reads

Create a Music Player using React-Native
React Native is a powerful framework that allows you to build mobile applications using JavaScript and React. In this tutorial, we are going to build a Music Player using React-Native. Here we will load the music files stored in our device and then use the play and pause button to control the music. We can also see the progress of the music played
4 min read
How to create Music Player UI Controls Component in ReactJS?
Crafting a basic music player UI in ReactJS becomes a straightforward endeavor with a simple and easily implementable logic. Leveraging Material UI for React further simplifies the process, offering an available component that seamlessly integrates into the project. Prerequisites:Node JS or NPMReact JSMaterial UIApproach:Functional Component Setup:
3 min read
Music Player using Django
In this article, we'll build a Music Player using Django. To get started, the first thing we'll do is create an account, just like with other music players. After creating the account, we'll log in. Once successfully logged in, we'll be redirected to the home page. On the home page, we can search for songs based on our preferences we used an API to
12 min read
Building a Music Player in React
The "Music Player" project is a web application built using React that offers users an interface to play, pause, and manage their music collection. It has a responsive design making it effortless for users to enjoy their songs. It has a separate data file using which the users can add their own songs to the list and can listen to their personalized
9 min read
Music Player App with Next.js and API
In this tutorial, we'll create a Music Player App using NextJS, a React framework. Explore frontend development, API integration, and UI design to build a user-friendly app for seamless music enjoyment. Join us in harmonizing code and creativity to craft an engaging Music Player App with NextJS in the digital age. Output Preview: Let us have a look
3 min read
Create a Music Website Template using HTML, CSS &amp; JavaScript
A Music Website Template is a pre-designed layout for creating a music-themed webpage. By utilizing HTML, CSS, and JavaScript, developers can craft a functional and visually appealing website with features like play/pause controls, sections for home, music, about, and contact. Approach: We will create the basic layout i.e. two divs (left and right)
3 min read
Create a Video Player App using React-Native
React-Native is an open-source JavaScript framework used to broaden cross-platform packages i.e., you may write code in React-Native and publish it as an Android or IOS app. In this article, we will build a Video Player app with the usage of React-Native. The app will run on both Android and IOS. Preview of the Final Output: Let us have a look at h
4 min read
Custom Video Player using HTML, CSS and JavaScript
In this article, we are going to implement a Custom Video Player using HTML CSS JavaScript. We will be using HTML to structure our project, CSS for designing purpose and JavaScript will be used to provide the required functionality. Preview of final Output: Let us have a look at how the final output will look like: Prerequisites of Video PlayerHTML
6 min read
Project Idea | Build an AR based music learning platform using the MERN Stack
In this article, we will be building an AR-based web app called GuitAR. It teaches users to learn guitar by projecting the strings that are to be plucked on the guitar in the user's camera feed. Now, all the user has to do is to pluck the highlighted strings to play a particular song. Here is an sample image for better understanding. [caption width
19 min read
Music Playlist App using MERN Stack
This tutorial will create a Music Playlist App using the MERN (MongoDB, Express.js, React.js, Node.js) stack. The app allows users to manage playlists, add songs, and play their favorite tracks. We'll cover front and backend development, integrating features like song uploading, playlist creation, and playback functionality. Output Preview: Let us
10 min read