Music Player using HTML, CSS & JavaScript

shobhitdev
19 Min Read

Creating a music player from scratch is an excellent way to enhance your skills in HTML, CSS, and JavaScript. This project will guide you through the process of building a simple yet functional music player app. By the end, you’ll have a deeper understanding of how these technologies work together to create interactive web applications.

Project Overview

In this project, you will learn how to build a Music Player app using HTML, CSS, and JavaScript. The app features a visually appealing album cover slider using Swiper JS and controls to play, pause, and navigate through songs.

Music Player Video Preview

Download Button

Step-by-Step Guide

1. HTML Structure

Start by creating the basic structure of your HTML document. This will include the album cover slider and the music player controls.

				
					<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Music Player with Slider | Swiper JS By Shobhitdev</title>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css'>
<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css'><link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<body>
    <div class="album-cover">
      <div class="swiper">
        <div class="swiper-wrapper">
          <div class="swiper-slide">
            <!-- shree ram -->
            <img decoding="async"
              src="https://w0.peakpx.com/wallpaper/202/932/HD-wallpaper-shree-ram-sun-background-lord-ram-god.jpg" />
            <div class="overlay">
              <a href="https://www.youtube.com/watch?v=aatr_2MstrI&amp;ab_channel=CleanBandit" target="_blank" rel="nofollow noopener"><ion-icon name="logo-youtube"></ion-icon
              ></a>
            </div>
          </div>
          <div class="swiper-slide">
            <!-- shree krishna image -->
            <img decoding="async"
              src="https://www.shyamparivar.com/uploads/gallery/best-shri-krishna-wallpaper-hd.jpg" />

          </div>
          <div class="swiper-slide">
            <!-- shree ram image -->
            <img decoding="async"
              src="https://qph.cf2.quoracdn.net/main-qimg-2ff30e6942579741b39a9bfa4462285f" />
            <div class="overlay">
              <a href="https://www.youtube.com/watch?v=h5oHhGlWKf0&amp;ab_channel=MuzikPlay" target="_blank" rel="nofollow noopener"><ion-icon name="logo-youtube"></ion-icon
              ></a>
            </div>
          </div>
          <div class="swiper-slide">
<!-- hanuman ji image -->

            <img decoding="async"
              src="https://media.licdn.com/dms/image/D4D12AQHSMDOPb9YPhg/article-cover_image-shrink_720_1280/0/1684390609012?e=2147483647&v=beta&t=IBa97pBYsaCt7jk1A4xMjTu3vyj5XR0V4hSpTkLb2Ks" />
            <div class="overlay">
              <a href="https://www.youtube.com/watch?v=a5uQMwRMHcs&amp;ab_channel=DaftPunkVEVO" target="_blank" rel="nofollow noopener"><ion-icon name="logo-youtube"></ion-icon
              ></a>
            </div>
          </div>
          <div class="swiper-slide">
            <!-- mahadev -->
            <img decoding="async"
              src="https://i.pinimg.com/736x/3f/61/d3/3f61d391f49a3996c1c323fb809f7a95.jpg" />
            <div class="overlay">
              <a href="https://www.youtube.com/watch?v=H5v3kku4y6Q&amp;ab_channel=HarryStylesVEVO" target="_blank" rel="nofollow noopener"><ion-icon name="logo-youtube"></ion-icon
              ></a>
            </div>
          </div>
          <div class="swiper-slide">
            <!-- ganesh -->
            <img decoding="async"
              src="https://img10.hotstar.com/image/upload/f_auto/sources/r1/cms/prod/3275/1393275-i-03928152b533" />
            <div class="overlay">
              <a href="https://www.youtube.com/watch?v=9HDEHj2yzew&amp;ab_channel=DuaLipa" target="_blank" rel="nofollow noopener"><ion-icon name="logo-youtube"></ion-icon
              ></a>
            </div>
          </div>
          <div class="swiper-slide">
            <!-- vishnu bhagwaan  -->
            <img decoding="async"
              src="https://w0.peakpx.com/wallpaper/394/1015/HD-wallpaper-dhyan-me-lin-vishnu-bhagwan-vishnu-bhagwan-bhakti.jpg" />
            <div class="overlay">
              <a href="https://www.youtube.com/watch?v=tCXGJQYZ9JA&amp;ab_channel=TaylorSwiftVEVO" target="_blank" rel="nofollow noopener"><ion-icon name="logo-youtube"></ion-icon
              ></a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="music-player">
      <h1 id="title" class="rb-heading-index-4">Title</h1>
      <p>Song Name</p>

      <audio id="song">
        <source src="song-list/Luke-Bergs-Gold.mp3" type="audio/mpeg" />
      </audio>

      <input type="range" value="0" id="progress" />

      <div class="controls">
        <button class="backward">
          <i class="fa-solid fa-backward"></i>
        </button>
        <button class="play-pause-btn">
          <i class="fa-solid fa-play" id="controlIcon"></i>
        </button>
        <button class="forward">
          <i class="fa-solid fa-forward"></i>
        </button>
      </div>
    </div>
  </body>
<!-- partial -->
  <script src='https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js'></script>
<script src='https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js'></script>
<script src='https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js'></script><script  src="./script.js"></script>

</body>
</html>

				
			

The HTML code sets up the structure of the Music Player and includes the necessary external resources and internal components.

  1. HTML Document Setup

    • The document starts with the <!DOCTYPE html> declaration, which defines the document type and version of HTML.
    • The <html lang="en"> tag specifies the language of the document as English.
  2. Head Section

    • The <head> section includes meta tags and links to external stylesheets:
      • <meta charset="UTF-8"> ensures proper encoding of characters.
      • <title>Music Player with Slider | Swiper JS By Shobhitdev</title> sets the title of the webpage.
      • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/..."> links to Font Awesome for icon usage.
      • <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/..."> links to Swiper JS stylesheet for slider functionality.
      • <link rel="stylesheet" href="./style.css"> links to the custom CSS file for additional styling.
  3. Body Section

    • The <body> section contains the main content of the Music Player:
      • Album Cover Section: This section contains the Swiper slider.
        • <div class="album-cover">: A container for the album cover images.
        • <div class="swiper">: A Swiper container that holds the slides.
        • <div class="swiper-wrapper">: A wrapper for individual slides.
          • Each <div class="swiper-slide"> represents a slide containing an album cover image and an optional overlay with a link.
          • Images are embedded using the <img src="..."> tag, and overlays are created with <div class="overlay"> containing links with <a href="..."><ion-icon name="..."></ion-icon></a>.
  4. Music Player Section

    • <div class="music-player">: A container for the music player controls.
      • <h1>Title</h1>: Placeholder for the song title.
      • <p>Song Name</p>: Placeholder for the artist’s name.
      • <audio id="song">: The audio element that plays the music, with a <source> tag pointing to the music file.
      • <input type="range" value="0" id="progress">: A range input to display and control the playback progress.
      • Control Buttons: Buttons for playback control.
        • <div class="controls">: A container for the control buttons.
        • <button class="backward"><i class="fa-solid fa-backward"></i></button>: Button for going to the previous track.
        • <button class="play-pause-btn"><i class="fa-solid fa-play" id="controlIcon"></i></button>: Button for play/pause functionality.
        • <button class="forward"><i class="fa-solid fa-forward"></i></button>: Button for going to the next track.
  5. Scripts

    • Scripts are included at the end of the body to enhance functionality:
      • <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>: Includes Swiper JS library.
      • <script src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>: Includes Ionicons library for icons.
      • <script src="./script.js"></script>: Includes the custom JavaScript file for interactivity.

2. CSS Styling

Next, style your music player and slider to make it visually appealing. Use CSS to define the layout, colors, and transitions.

				
					/* © 2024. shobhitDev All rights reserved. */
@import url("https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;500;600&display=swap");

:root {
  --primary-clr: rgba(228, 228, 229, 1);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Nunito", sans-serif;
}

body {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  width: 100%;
  background: url(https://github.com/ecemgo/mini-samples-great-tricks/assets/13468728/8727c9b1-be21-4932-a221-4257b59a74dd);
  background-repeat: no-repeat;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  animation: slidein 120s forwards infinite alternate;
}

@keyframes slidein {
  0%,
  100% {
    background-position: 20% 0%;
    background-size: 3400px;
  }
  50% {
    background-position: 100% 0%;
    background-size: 2400px;
  }
}

.album-cover {
  width: 90%;
}

.swiper {
  width: 100%;
  padding: 40px 0 100px;
}

.swiper-slide {
  position: relative;
  max-width: 200px;
  aspect-ratio: 1/1;
  border-radius: 10px;
}

.swiper-slide img {
  object-fit: cover;
  width: 100%;
  height: 100%;
  border-radius: inherit;
  -webkit-box-reflect: below -5px linear-gradient(transparent, transparent, rgba(0, 0, 0, 0.4));
  transform-origin: center;
  transform: perspective(800px);
  transition: 0.3s ease-out;
  pointer-events: none;
  user-select: none;
}

.swiper-slide-active .overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  inset: 0;
  width: 100%;
  height: 98%;
  background-color: rgba(28, 22, 37, 0.6);
  border-radius: inherit;
  opacity: 0;
  transition: all 0.4s linear;
}

.swiper-slide:hover .overlay {
  opacity: 1;
}

.swiper-slide .overlay ion-icon {
  opacity: 0;
}

.swiper-slide-active:hover .overlay ion-icon {
  font-size: 4rem;
  color: #eb0b0b;
  opacity: 1;
  cursor: pointer;
}

/* Music Player */

.music-player {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: var(--primary-clr);
  width: 380px;
  padding: 10px 30px;
  border-radius: 20px;
}

.music-player h1 {
  font-size: 1.5rem;
  font-weight: 600;
  line-height: 1.6;
}

.music-player p {
  font-size: 1rem;
  font-weight: 400;
  opacity: 0.6;
}

/* Music Player Progress */

#progress {
  appearance: none;
  -webkit-appearance: none;
  width: 100%;
  height: 7px;
  background: rgba(163, 162, 164, 0.4);
  border-radius: 4px;
  margin: 32px 0 24px;
  cursor: pointer;
}

#progress::-webkit-slider-thumb {
  appearance: none;
  -webkit-appearance: none;
  background: rgba(163, 162, 164, 0.9);
  width: 16px;
  aspect-ratio: 1/1;
  border-radius: 50%;
  outline: 4px solid var(--primary-clr);
  box-shadow: 0 6px 10px rgba(5, 36, 28, 0.3);
}

/* Music Player Controls */

.controls {
  display: flex;
  justify-content: center;
  align-items: center;
}

.controls button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  aspect-ratio: 1/1;
  margin: 20px;
  background: rgba(163, 162, 164, 0.3);
  color: var(--primary-clr);
  border-radius: 50%;
  border: 1px solid rgba(255, 255, 255, 0.3);
  outline: 0;
  font-size: 1.1rem;
  box-shadow: 0 10px 20px rgba(5, 36, 28, 0.3);
  cursor: pointer;
  transition: all 0.3s linear;
}

.controls button:is(:hover, :focus-visible) {
  transform: scale(0.96);
}

.controls button:nth-child(2) {
  transform: scale(1.3);
}

.controls button:nth-child(2):is(:hover, :focus-visible) {
  transform: scale(1.25);
}
/* © 2024. shobhitDev All rights reserved. */
				
			

The CSS code styles the Music Player and the image slider, ensuring it is visually appealing and functional.

Importing Fonts and Setting Variables

@import url(“https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;500;600&display=swap”);

:root {
–primary-clr: rgba(228, 228, 229, 1);
}

  • Font Import: The @import rule imports the “Nunito” font from Google Fonts.
  • CSS Variables: The :root selector defines a primary color variable --primary-clr for easy color management throughout the project.

Reset and Basic Styling

* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: “Nunito”, sans-serif;
}

  • Universal Selector: The * selector resets margin and padding to zero and sets box-sizing to border-box for all elements to ensure consistency.
  • Font Family: Applies the “Nunito” font to all elements.

Body Styling

body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #333;
color: white;
font-family: “Nunito”, sans-serif;
}

  • Flexbox Layout: Centers the content horizontally and vertically using display: flex, justify-content: center, and align-items: center.
  • Full Height: Sets the body height to 100% of the viewport height (100vh).
  • Background and Text Color: Sets the background color to dark gray (#333) and text color to white.

Music Player Container

.music-player {
background-color: #444;
border-radius: 10px;
padding: 20px;
width: 300px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}

  • Background Color: Sets the background color to a lighter gray (#444).
  • Rounded Corners: Applies a border-radius of 10px for rounded corners.
  • Padding: Adds 20px padding inside the container.
  • Fixed Width: Sets the width of the container to 300px.
  • Box Shadow: Adds a shadow effect for a subtle 3D appearance.

Album Cover Styling

.album-cover img {
width: 100%;
border-radius: 10px;
}

  • Full Width: Sets the album cover image to take up the full width of its container.
  • Rounded Corners: Applies a border-radius of 10px to the image.

Song Info

.song-info {
text-align: center;
margin: 10px 0;
}

  • Text Alignment: Centers the text within this element.
  • Margin: Adds a margin of 10px above and below the element.

Control Buttons

.controls {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 20px;
}

  • Flexbox Layout: Uses flexbox to arrange the control buttons.
  • Space Between: Distributes the space between buttons equally.
  • Alignment: Aligns the items in the center vertically.
  • Top Margin: Adds a 20px margin to the top of the controls section.

Individual Button Styling

.controls button {
background: none;
border: none;
color: white;
font-size: 20px;
cursor: pointer;
transition: transform 0.2s;
}
.controls button:hover {
transform: scale(1.2);
}

  • No Background or Border: Removes the default button background and border.
  • Text Color: Sets the button text color to white.
  • Font Size: Increases the font size to 20px.
  • Pointer Cursor: Changes the cursor to a pointer when hovering over the button.
  • Transition Effect: Adds a smooth scaling transition effect on hover.
  • Hover Effect: Scales the button up to 1.2 times its original size on hover.

This CSS code is designed to create a visually appealing and functional Music Player with responsive and interactive elements. It uses flexbox for layout management, CSS variables for easy color management, and smooth transitions for interactive elements like buttons.

3. JavaScript Functionality

Finally, use JavaScript to add functionality to your music player. This includes playing, pausing, navigating through songs, and updating the progress bar.

				
					// © 2024. shobhitDev All rights reserved.
const progress = document.getElementById("progress");
const song = document.getElementById("song");
const controlIcon = document.getElementById("controlIcon");
const playPauseButton = document.querySelector(".play-pause-btn");
const forwardButton = document.querySelector(".controls button.forward");
const backwardButton = document.querySelector(".controls button.backward");
const songName = document.querySelector(".music-player h1");
const artistName = document.querySelector(".music-player p");

const songs = [
  {
    title: "Ram Aayenge 🚩",
    name: "Ram Aayenge 🚩By Shobhit Asthana",
    source:
      "Ram Aayenge.m4a",
  },
  {
    title: "ADHARAM MADHURAM",
    name: "ADHARAM MADHURAM By Shobhit Asthana",
    source:
      "ADHARAM MADHURAM.m4a",
  },
  {
    title: "Ram Aayenge 🚩",
    name: "Ram Aayenge 🚩By Shobhit Asthana",
    source:
      "Ram Aayenge.m4a",
  },
  {
    title: "Keejo Kesari Ke Laal",
    name: "Keejo Kesari Ke Laal By Shobhit Asthana",
    source:
      "Keejo Kesari Ke Laal.m4a",
  },
  {
    title: "Shiv Tandav Stotram",
    name: "Shiv Tandav Stotram By Shobhit Asthana",
    source:
      "Shiv Tandav Stotram.m4a",
  },

  {
    title: "ganpati bappa morya 🙏🙏🚩🚩❤️❤️❤️❤️",
    name: "ganpati bappa morya 🙏🚩❤️ by Shobhit Asthana",
    source:
      "ganpati bappa morya.m4a",
  },
  {
    title: "Shakti Hai Bhakti Hai",
    name: "Shakti Hai Bhakti Hai By Shobhit Ashana",
    source:
      "Shakti Hai Bhakti Hai.m4a",
  },
];

let currentSongIndex = 3;

function updateSongInfo() {
  songName.textContent = songs[currentSongIndex].title;
  artistName.textContent = songs[currentSongIndex].name;
  song.src = songs[currentSongIndex].source;

  song.addEventListener("loadeddata", function () {});
}

song.addEventListener("timeupdate", function () {
  if (!song.paused) {
    progress.value = song.currentTime;
  }
});

song.addEventListener("loadedmetadata", function () {
  progress.max = song.duration;
  progress.value = song.currentTime;
});

function pauseSong() {
  song.pause();
  controlIcon.classList.remove("fa-pause");
  controlIcon.classList.add("fa-play");
}

function playSong() {
  song.play();
  controlIcon.classList.add("fa-pause");
  controlIcon.classList.remove("fa-play");
}

function playPause() {
  if (song.paused) {
    playSong();
  } else {
    pauseSong();
  }
}

playPauseButton.addEventListener("click", playPause);

progress.addEventListener("input", function () {
  song.currentTime = progress.value;
});

progress.addEventListener("change", function () {
  playSong();
});

forwardButton.addEventListener("click", function () {
  currentSongIndex = (currentSongIndex + 1) % songs.length;
  updateSongInfo();
  playPause();
});

backwardButton.addEventListener("click", function () {
  currentSongIndex = (currentSongIndex - 1 + songs.length) % songs.length;
  updateSongInfo();
  playPause();
});

updateSongInfo();

var swiper = new Swiper(".swiper", {
  effect: "coverflow",
  centeredSlides: true,
  initialSlide: 3,
  slidesPerView: "auto",
  allowTouchMove: false,
  spaceBetween: 40,
  coverflowEffect: {
    rotate: 25,
    stretch: 0,
    depth: 50,
    modifier: 1,
    slideShadows: false,
  },
  navigation: {
    nextEl: ".forward",
    prevEl: ".backward",
  },
});
// © 2024. shobhitDev All rights reserved.
				
			

The JavaScript code handles the logic for playing, pausing, and navigating through songs in the Music Player.

HTML Setup for JavaScript

Ensure the following HTML structure for the JavaScript code to work correctly:

<div class=”music-player”>
<div class=”album-cover”>
<img src=”album-cover1.jpg” alt=”Album Cover”>
</div>
<div class=”song-info”>
<h2 id=”title”>Song Title</h2>
<h3 id=”artist”>Artist Name</h3>
</div>
<div class=”controls”>
<button id=”prev”>Prev</button>
<button id=”play”>Play</button>
<button id=”next”>Next</button>
</div>
</div>
<audio id=”audio”></audio>

JavaScript Code

Initialization

const songs = [
{
name: “song1”,
title: “Song Title 1”,
artist: “Artist 1”,
cover: “cover1.jpg”,
src: “song1.mp3”
},
{
name: “song2”,
title: “Song Title 2”,
artist: “Artist 2”,
cover: “cover2.jpg”,
src: “song2.mp3”
},
{
name: “song3”,
title: “Song Title 3”,
artist: “Artist 3”,
cover: “cover3.jpg”,
src: “song3.mp3”
}
];

let currentSongIndex = 0;
const audio = document.getElementById(“audio”);
const playButton = document.getElementById(“play”);
const prevButton = document.getElementById(“prev”);
const nextButton = document.getElementById(“next”);
const title = document.getElementById(“title”);
const artist = document.getElementById(“artist”);
const albumCover = document.querySelector(“.album-cover img”);

  • Songs Array: Contains objects representing each song with properties for name, title, artist, cover, and src.
  • Index Initialization: Initializes currentSongIndex to keep track of the current song.
  • Element Selection: Selects HTML elements for manipulation (audio, playButton, prevButton, nextButton, title, artist, albumCover).

Loading Songs

function loadSong(song) {
title.textContent = song.title;
artist.textContent = song.artist;
albumCover.src = song.cover;
audio.src = song.src;
}

loadSong(songs[currentSongIndex]);

  • Load Song Function: Updates the song title, artist, album cover, and audio source based on the current song.
  • Initial Load: Loads the first song using loadSong.

Play and Pause Functionality

let isPlaying = false;

function playSong() {
isPlaying = true;
audio.play();
playButton.textContent = “Pause”;
}

function pauseSong() {
isPlaying = false;
audio.pause();
playButton.textContent = “Play”;
}

playButton.addEventListener(“click”, () => {
if (isPlaying) {
pauseSong();
} else {
playSong();
}
});

  • Play Song Function: Sets isPlaying to true, plays the audio, and changes the play button text to “Pause”.
  • Pause Song Function: Sets isPlaying to false, pauses the audio, and changes the play button text to “Play”.
  • Play Button Event Listener: Toggles between play and pause states when the play button is clicked.

Next and Previous Functionality

function nextSong() {
currentSongIndex = (currentSongIndex + 1) % songs.length;
loadSong(songs[currentSongIndex]);
if (isPlaying) {
playSong();
}
}

function prevSong() {
currentSongIndex = (currentSongIndex – 1 + songs.length) % songs.length;
loadSong(songs[currentSongIndex]);
if (isPlaying) {
playSong();
}
}

nextButton.addEventListener(“click”, nextSong);
prevButton.addEventListener(“click”, prevSong);

  • Next Song Function: Increments currentSongIndex, wraps around using the modulo operator, loads the next song, and plays it if a song was already playing.
  • Previous Song Function: Decrements currentSongIndex, ensures it wraps correctly using the modulo operator, loads the previous song, and plays it if a song was already playing.
  • Button Event Listeners: Adds click event listeners to the next and previous buttons to navigate through the songs.

This JavaScript code is designed to control the functionality of the Music Player, including loading songs, playing and pausing, and navigating through the playlist. It uses event listeners for user interactions and ensures the player updates the UI and audio source accordingly.

Summary

This guide helps you create a functional and stylish music player with an album cover slider using HTML, CSS, and JavaScript. The project demonstrates the integration of Swiper JS for the slider and basic audio control features, giving you a comprehensive learning experience. Enjoy building your music player!

Share This Article
Leave a comment