Custom Music Player with JavaScript

Custom Music Player with JavaScript & HTML (Free Code)

Do you want to create music player using javascript? If your answer is yes then this article is for you.

In this tutorial you will learn how to create a simple javascript audio player. This is a basic javascript music player but I built it with all kinds of options.

Earlier I shared a tutorial on an html5 audio player. But it’s very basic and doesn’t have all the advanced features. If you know basic JavaScript then you will hopefully like this web music player javascript project.

Custom Music Player with JavaScript

In this music player html css we can control and change the music. Besides, I can see the monthly image and progress. I made the basic structure of this simple javascript audio player with html. Then designed it by css. Finally, I activated the web music player project by JavaScript.

Build a Music Player Using JavaScript – Free Demo + Code

There are many tutorials on the internet to create this project (Build a Music Player using HTML CSS & JavaScript) but this article will be the best for you. Because here I have made this Music Player with JavaScript very simple keeping the beginners in mind. In addition, I have explained JavaScript step by step.

javascript music player

JavaScript music player refers to a player that is built using JavaScript programming language. This type of music player can be used to play audio files on a website or web application. It can be implemented as a standalone player or integrated into a larger application. JavaScript music players typically use HTML5’s audio API to play audio files, although here are created by pure JavaScript.

There are many ways to create a custom web music player project. both as standalone libraries and as plugins for popular front-end frameworks like React and Angular. Some popular JavaScript music players include. Below I have given a preview of this Music Player JavaScript. Hopefully you can understand how it works.

See the Pen Custom Music Player with JavaScript by Ground Tutorial (@groundtutorial) on CodePen.

As you can see in the preview above it is a very nicely made javascript music player with playlist. Here first I have created a box on the web page in which you can see some function buttons and an image. That image is basically the image of the music, here if you change the music, the image will change.

Another box will appear when we play the music. In that box we will see progress now which will help to backward and forward the music. That box will hide again when we close the music.

Create Custom Music Player in JavaScript

There are many tutorials on the internet from which you can create Custom Music Player. But there is no good explanation for beginners.

Here you will find music player javascript code, live preview, necessary explanation and step by step guide. If you only want the source code, you can use the source code button below the article.

Step 1: Basic structure of JavaScript Music Player

Using these HTML and css codes I created a basic structure for this music player. Within this basic structure, we will add all the information.

This Custom JavaScript Music Player has no fixed width or height, it will set its own size based on the amount of content and padding: 20px 30px.

				
					<div class="music-container" id="music-container">
 
</div>
				
			
				
					* {
  box-sizing: border-box;
}

body {
  background-color: #345d80;
  font-family: "Rubik", sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
}

.music-container {
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 3px 10px 0 rgba(186, 184, 184, 0.6);
  display: flex;
  padding: 20px 30px;
  position: relative;
  margin: 100px 0;
  z-index: 10;
}
				
			
Basic structure of JavaScript Music Player

Step 2: Add progress bar to Music Player

Now we need to create a music progress bar box. In this box we can change the duration of the music and rewind the music. Here opacity: 0 is used which means this box will not be visible in normal state.

As you can see in the preview we can see a box of Music Player and a box that doesn’t. When we are playing the music we can see this progress bar box.

				
					<div class="music-info">
  <h2 id="title" class="title"></h2>
  <div class="progress-container" id="progress-container">
    <div class="progress" id="progress"></div>
  </div>
</div>
				
			
				
					.music-info {
  background-color: rgba(255,255,255,0.5);
  border-radius: 15px 15px 0 0;
  position: absolute;
  width: calc(100% - 40px);
  padding: 10px 10px 10px 150px;
  top: 0;
  left: 20px;
  opacity: 0;
  transform: translateY(0%);
  transition: transform 0.3s ease-in, opacity 0.3s ease-in;
  z-index: 0;
}

.music-container.play .music-info {
  opacity: 1;
  transform: translateY(-100%);
}

.music-info h2 {
  font-size: 1rem;
  font-weight: bold;
  margin: 0;
}

.progress-container {
  background-color: #fff;
  border-radius: 5px;
  cursor: pointer;
  margin: 10px 0;
  height: 4px;
  width: 100%;
}

.progress {
  background-color: #fe8daa;
  border-radius: 5px;
  height: 100%;
  width: 0%;
  transition: width 0.1s linear;
}
				
			

Step 3: Add song and image to javascript audio player

Now in the javascript audio player we have added the audio and added an image related to it. Then I designed that image with the following css. Here I have used an image height: 110px and border-radius: 50% to make it completely round. 

The image in this music player will cycle. I used transform: rotate to make it. Which will continuously rotate it through 360-degree angle.

				
					<audio src="https://github.com/bradtraversy/vanillawebprojects/blob/master/music-player/music/summer.mp3?raw=true"
        id="audio"></audio>
<div class="img-container">
<img data-lazyloaded="1" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzNTgiIGhlaWdodD0iMjM5IiB2aWV3Qm94PSIwIDAgMzU4IDIzOSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgc3R5bGU9ImZpbGw6I2NmZDRkYjtmaWxsLW9wYWNpdHk6IDAuMTsiLz48L3N2Zz4=" width="358" height="239" decoding="async" data-src="https://github.com/bradtraversy/vanillawebprojects/blob/master/music-player/images/summer.jpg?raw=true"
          alt="music-cover"
          id="cover" />
</div>
				
			
				
					.img-container {
  position: relative;
  width: 110px;
}

.img-container img {
  border-radius: 50%;
  object-fit: cover;
  height: 110px;
  width: inherit;
  position: absolute;
  bottom: 0;
  left: 0;
  animation: rotateImage 3s linear infinite;
  animation-play-state: paused;
}

.img-container::after {
  content: '';
  position: absolute;
  background-color: #fff;
  border-radius: 50%;
  bottom: 100%;
  left: 50%;
  height: 20px;
  width: 20px;
  transform: translate(-50%, 50%);
}

.music-container.play .img-container img {
  animation-play-state: running;
}

@keyframes rotateImage {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
				
			
Add song and image to javascript audio player

Step 4: Add control option to Music Player

Now we need to add control options in the javascript music player with playlist. Here we have added three buttons Backward, Play, and Forward. With this button, we can change and stop the previous music.

				
					<div class="navigation">
  <button id="prev" class="action-btn">
    <i class="fas fa-backward"></i>
  </button>
  <button id="play" class="action-btn action-btn-big">
    <i class="fas fa-play"></i>
  </button>
  <button id="next" class="action-btn">
    <i class="fas fa-forward"></i>
  </button>
</div>
				
			
				
					.navigation {
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.action-btn {
  background-color: #fff;
  border: 0;
  color: #490349;
  font-size: 20px;
  cursor: pointer;
  padding: 10px;
  margin: 0 20px;
}

.action-btn:focus {
  outline: none;
}

.action-btn:hover, .action-btn.action-btn-big:hover {
  color: #8d91fe;
}

.action-btn.action-btn-big {
  color: #0c085f;
  font-size: 30px;
}
				
			
Add control option to Music Player

Step 5: Activate Music Player with JavaScript

As you can see we have done the music player javascript design. Now we need to use javascript to make it work. Hope you will not have any difficulty in understanding the following codes as I have given step by step explanation here.

1. Create variables to store Music Player's data

This code defines several variables that represent elements on the page. The musicContainer, playButton, prevButton, nextButton, audio, progress, progressContainer, title, and cover variables are used to store references to elements on the page using their id values.

The songs array stores a list of song names, and the songIndex variable is used to keep track of the current song that is being played.

				
					const musicContainer = document.getElementById("music-container");
const playButton = document.getElementById("play");
const prevButton = document.getElementById("prev");
const nextButton = document.getElementById("next");
const audio = document.getElementById("audio");
const progress = document.getElementById("progress");
const progressContainer = document.getElementById("progress-container");
const title = document.getElementById("title");
const cover = document.getElementById("cover");

const songs = ["hey", "summer", "ukulele"];
let songIndex = 1;
				
			

The code sets up references to elements on the page that will be used to control the javascript music player, such as the play and pause buttons, the previous and next buttons, and the audio element that will be used to play the music. The code also sets up references to other elements on the page, such as the title and cover, that may be used to display information about the current song.

2. Capitalize the audio titles of the JavaScript music player

This function getSongTitle takes in a song name as a parameter and returns a capitalized version of the song name. The function first uses the charAt method to get the first character of the song name, then uses the toUpperCase method to convert it to uppercase. Finally, the slice method is used to get all characters after the first one and concatenate them with the capitalized first character to form the capitalized song title.

				
					function getSongTitle(song) {
  return song.charAt(0).toUpperCase() + song.slice(1);
}
				
			

This function can be useful for formatting the song names before displaying them on the page, as it ensures that the first letter of each song name is capitalized.

3. Load song name as a parameter

This function loadSong takes in a song name as a parameter and loads the song and its associated information into the music player. The function starts by calling the getSongTitle function to format the song name, and then sets the innerText property of the title element to the capitalized song name.

				
					function loadSong(song) {
  title.innerText = getSongTitle(song);
  audio.src = `https://github.com/bradtraversy/vanillawebprojects/blob/master/music-player/music/${song}.mp3?raw=true`;
  cover.src = `https://github.com/bradtraversy/vanillawebprojects/blob/master/music-player/images/${song}.jpg?raw=true`;
}
				
			

Next, the src property of the audio element is set to the URL of the MP3 file for the song. This URL is constructed using template literals by concatenating the string "https://github.com/bradtraversy/vanillawebprojects/blob/master/music-player/music/" with the song name and the string ".mp3?raw=true".

Finally, the src property of the cover element is set to the URL of the image file for the song. This URL is constructed in a similar way as the URL for the audio file, but points to an image file instead.

4. start playing a song in the music player with javascript

This function playSong is used to start playing a song in the music player with javascript. The function starts by adding the class “play” to the musicContainer element. This class can be used in CSS to apply styles that are specific to the playing state of the player, such as displaying the album cover or hiding the play button.

Next, the function uses the querySelector method to get the first i element with the class “fas” that is a descendant of the playButton element. The classList property is then used to remove the “fa-play” class and add the “fa-pause” class to this element. The “fa-play” and “fa-pause” classes are likely part of the Font Awesome library, and are used to display play and pause icons, respectively.

				
					function playSong() {
  musicContainer.classList.add("play");
  playButton.querySelector("i.fas").classList.remove("fa-play");
  playButton.querySelector("i.fas").classList.add("fa-pause");
  audio.play();
}
				
			

Finally, the play method is called on the audio element to start playing the song.

This function is typically called in response to a user clicking the play button. When the song is playing, the function can be used to update the state of the player to reflect this, such as by changing the play button to a pause button and displaying the album cover.

5. Pause a song that is currently playing in the music player

This function pauseSong is used to pause a song that is currently playing in the JavaScript music player. The function starts by removing the class “play” from the musicContainer element. This class can be used in CSS to apply styles that are specific to the playing state of the player, such as displaying the album cover or hiding the play button.

				
					function pauseSong() {
  musicContainer.classList.remove("play");
  playButton.querySelector("i.fas").classList.remove("fa-pause");
  playButton.querySelector("i.fas").classList.add("fa-play");
  audio.pause();
}
				
			

Next, the function uses the querySelector method to get the first i element with the class “fas” that is a descendant of the playButton element. The classList property is then used to remove the “fa-pause” class and add the “fa-play” class to this element. The “fa-play” and “fa-pause” classes are likely part of the Font Awesome library, and are used to display play and pause icons, respectively.

6. Play the previous song in the javascript music player

This function prevSong is used to play the previous song in the javascript music player playlist. The function starts by decrementing the songIndex variable, which keeps track of the current song in the playlist.

Next, the function checks if the songIndex is less than 0. If it is, it means that the first song in the playlist is currently playing, so the songIndex is set to the index of the last song in the playlist. This is done by setting songIndex to songs.length - 1. The songs array contains the names of all the songs in the playlist.

				
					function prevSong() {
  songIndex--;
  if (songIndex < 0) songIndex = songs.length - 1;
  loadSong(songs[songIndex]);
  playSong();
}
				
			

Finally, the function calls the loadSong function and passes it the current song in the music playlist. The loadSong function is used to load the audio and album cover for a given song.

Once the song has been loaded, the playSong function is called to start playing the song.

This function is typically called in response to a user clicking the previous button in the player. The function allows the user to skip to the previous song in the playlist, and starts playing that song.

7. Play the next song in the Custom Music Player

This function nextSong is used to play the next song in the playlist. The function starts by incrementing the songIndex variable, which keeps track of the current song in the playlist.

Once the song has been loaded, the playSong function is called to start playing the song.

				
					function nextSong() {
  songIndex++;
  if (songIndex > songs.length - 1) songIndex = 0;
  loadSong(songs[songIndex]);
  playSong();
}
				
			

8. Update and set the progress bar in the music player

These two functions, updateProgress and setProgress, are used to update and set the progress bar in the music player javascript.

The updateProgress function takes an event as a parameter and is used to update the width of the progress bar to reflect the current time of the song being played. 

The function starts by destructuring the duration and currentTime properties from the audio element. The duration property is the total length of the song and currentTime is the current time of the song that is being played.

				
					function updateProgress(e) {
  const { duration, currentTime } = e.srcElement;
  const progressPercent = (currentTime / duration) * 100;
  progress.style.width = `${progressPercent}%`;
}

function setProgress(e) {
  const width = this.clientWidth;
  const clickX = e.offsetX;
  const duration = audio.duration;
  audio.currentTime = (clickX / width) * duration;
}
				
			

Next, the function calculates the progress percent of the song by dividing the currentTime by the duration and multiplying it by 100. The progress percent is then used to set the width of the progress bar.

The setProgress function is used to set the current time of the song to the position of the progress bar where the user clicked. The function starts by getting the width of the progress container and the x-coordinate of the click event. It then calculates the new currentTime of the song by dividing the click x-coordinate by the width of the container and multiplying it by the duration of the song.

9. Various buttons and elements in the music player

These are the event listeners for the various buttons and elements in the music player Custom Music Player with JavaScript.

The playButton has an event listener attached to it that listens for a click event. When the button is clicked, it checks if the musicContainer element has a class of “play”. If it does, then it pauses the song by calling the pauseSong function. If it doesn’t, it plays the song by calling the playSong function.

				
					// Event Listeners
playButton.addEventListener("click", () => {
  const isPlaying = musicContainer.classList.contains("play");
  isPlaying ? pauseSong() : playSong();
});

prevButton.addEventListener("click", prevSong);
nextButton.addEventListener("click", nextSong);

audio.addEventListener("timeupdate", updateProgress);
progressContainer.addEventListener("click", setProgress);

audio.addEventListener("ended", nextSong);
				
			

The prevButton and nextButton elements have event listeners attached to them that listen for a click event. When either button is clicked, it calls the prevSong or nextSong function, respectively.

The audio element has an event listener attached to it that listens for the timeupdate event. When this event is triggered, the updateProgress function is called to update the progress bar of the music player.

The progressContainer element has an event listener attached to it that listens for a click event. When this event is triggered, the setProgress function is called to set the current time of the song to the position of the progress bar where the user clicked.

10. Called and passed the song

The loadSong function is called and passed the song at the songIndex from the songs array. This loads the song and updates the title, audio source, and cover image for the music player in JavaScript.

				
					loadSong(songs[songIndex]);
				
			
Custom Music Player with JavaScript

Hope from above tutorial you got to know how I made this project (How to make audio player in JavaScript).

If there is any problem, you can comment me. Earlier I shared another advanced video player tutorial. If you like the design of this music player in JavaScript, you can watch the video player tutorial. Please comment how you like this HTML and JavaScript audio player.

You can play an audio file in JavaScript using the HTML5 Audio object. Here’s an example of how you can play an audio file when the page loads:

<script>
window.onload = function() {
var audio = new Audio('path/to/audio.mp3');
audio.play();
}
</script>

In the code above, we create a new Audio object and pass the path to the audio file as a parameter. Then, we use the play() method to start playing the audio.

Note that the Audio object also provides other methods and properties that you can use to control the playback, such as pause(), currentTime, duration, etc.

To create an MP3 player in HTML, you can use the HTML5 audio element along with JavaScript to add controls and interact with the audio playback. Here’s a simple example of an MP3 player:

<audio id="player" src="path/to/audio.mp3"></audio>
<br>
<button id="playButton">Play</button>
<button id="pauseButton">Pause</button>

<script>
var player = document.getElementById("player");
var playButton = document.getElementById("playButton");
var pauseButton = document.getElementById("pauseButton");

playButton.addEventListener("click", function() {
player.play();
});

pauseButton.addEventListener("click", function() {
player.pause();
});
</script>

In the code above, we use the audio element to embed an audio file, and add buttons for play and pause controls. We then use JavaScript to bind event listeners to the buttons, which call the play() and pause() methods on the audio element respectively.

You can also add other controls such as volume, skip, and seek, and use the audio element’s properties and methods to interact with the audio playback and display information such as the current time and duration of the audio.

Here is a high-level overview of the steps to create a media player in JavaScript:

  1. Create an HTML file to define the structure and layout of your media player.
  2. Add HTML elements such as an audio or video tag to define the media source you want to play.
  3. Add JavaScript to control the playback of the media, such as play, pause, and stop buttons.
  4. Use JavaScript to create an interface to control the media player, such as volume control, time display, and progress bar.
  5. Style your media player using CSS to give it a visually appealing look and feel.
  6. Test your media player and make any necessary changes or modifications.