Coding classic

html, css, javascript, react, python

How to Make a Responsive Music Player with Slider Using Swiper JS, HTML, CSS & JavaScript

Building a Responsive Music Player with Slider using Swiper JS

This guide will walk you through creating a responsive music player with a slider feature using Swiper JS, HTML, CSS, and JavaScript. This project combines the power of Swiper JS for smooth slider functionality with the flexibility of HTML, CSS, and JavaScript for a visually appealing and interactive music player.

Introduction

The goal is to build a music player that adapts to different screen sizes and provides a user-friendly interface for navigating through a playlist. We’ll use Swiper JS to create a slider that displays the song titles and allows users to easily switch between tracks.

1. HTML (index.html):

This HTML code sets up a webpage with a music player that showcases album covers through a slider powered by the Swiper JS library. Each album cover serves as a link to a YouTube video. Beneath the slider, there is a music player equipped with play controls and a progress slider. Icons are provided by external libraries such as Font Awesome and Ionicons, while the functionality is managed by an external JavaScript file.

<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Sets the character encoding for the HTML document -->
  <meta charset="UTF-8">
  
  <!-- Title of the webpage, shown in the browser's title bar or tab -->
  <title>Music Player with Slider | Swiper JS</title>
  
  <!-- Link to the Font Awesome stylesheet for using icons -->
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css'>
  
  <!-- Link to the Swiper JS library's stylesheet for the slider functionality -->
  <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css'>
  
  <!-- Link to the custom CSS stylesheet for additional styles -->
  <link rel="stylesheet" href="./style.css">
</head>

<body>
<!-- Main content of the webpage starts here -->
  <div class="album-cover">
    <!-- Wrapper for the Swiper slider -->
    <div class="swiper">
      
      <!-- Container for the slides -->
      <div class="swiper-wrapper">
        
        <!-- Individual slide containing an album cover and a YouTube link -->
        <div class="swiper-slide">
          <!-- Image of the album cover -->
          <img src="/Images/image1.png" />
          
          <!-- Overlay with a YouTube icon linking to a video -->
          <div class="overlay">
            <a href="https://www.youtube.com/watch?v=aatr_2MstrI&ab_channel=CleanBandit" target="_blank">
              <ion-icon name="logo-youtube"></ion-icon>
            </a>
          </div>
        </div>
        
        <!-- Repeat the structure above for additional album covers -->
        <div class="swiper-slide">
          <img src="/Images/image2.png" />
          <div class="overlay">
            <a href="https://www.youtube.com/watch?v=qEnfeG8uBRY&ab_channel=AliciaKeys-Topic" target="_blank">
              <ion-icon name="logo-youtube"></ion-icon>
            </a>
          </div>
        </div>
        
        <!-- Additional slides continue here -->
        <!-- ... -->
        
      </div> <!-- End of swiper-wrapper -->
    </div> <!-- End of swiper -->
  </div> <!-- End of album-cover -->

  <!-- Music player section -->
  <div class="music-player">
    <!-- Display the title of the music player -->
    <h1>Title</h1>
    
    <!-- Display the name of the song -->
    <p>Song Name</p>

    <!-- Audio element for playing music, with the source file linked -->
    <audio id="song">
      <source src="song-list/Luke-Bergs-Gold.mp3" type="audio/mpeg" />
    </audio>

    <!-- Slider for displaying and controlling the progress of the song -->
    <input type="range" value="0" id="progress" />

    <!-- Control buttons for the music player -->
    <div class="controls">
      <!-- Button to skip backward -->
      <button class="backward">
        <i class="fa-solid fa-backward"></i>
      </button>
      
      <!-- Button to play or pause the music -->
      <button class="play-pause-btn">
        <i class="fa-solid fa-play" id="controlIcon"></i>
      </button>
      
      <!-- Button to skip forward -->
      <button class="forward">
        <i class="fa-solid fa-forward"></i>
      </button>
    </div>
  </div> <!-- End of music-player -->

<!-- JavaScript files loaded at the end for better performance -->
  <!-- Swiper JS library for the slider functionality -->
  <script src='https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js'></script>
  
  <!-- Ionicons library for YouTube icon -->
  <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>
  
  <!-- Link to custom JavaScript file for additional functionality -->
  <script src="./script.js"></script>
</body>
</html>

2. CSS Styling (style.css):

This CSS code styles a webpage with a focus on a music player and album display. It incorporates the Nunito font from Google Fonts for a clean and modern look. The background features a dynamic sliding animation, adding visual interest.

The album covers are showcased in a sleek Swiper slider, and when the user hovers over an album, a YouTube icon overlay appears, hinting at the possibility of watching music videos. The music player itself is designed with intuitive controls for playing, pausing, and navigating through tracks.

The progress slider indicates the current playback position, and the controls are enhanced with subtle hover effects and a slight scaling animation, providing a smooth and responsive user experience.

/* Importing the Nunito font from Google Fonts with multiple weights */
@import url("https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;500;600&display=swap");

/* Define a custom property (CSS variable) for primary color */
:root {
  --primary-clr: rgba(228, 228, 229, 1);
}

/* Reset default margins and paddings, set box-sizing and font family */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Nunito", sans-serif; /* Applies Nunito font to all elements */
}

/* Style for the body element */
body {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh; /* Full viewport height */
  width: 100%; /* Full viewport width */
  background: url(/Images/background.png); /* Background image */
  background-repeat: no-repeat; /* Prevents background image from repeating */
  backdrop-filter: blur(8px); /* Applies a blur effect to the background */
  -webkit-backdrop-filter: blur(8px); /* Vendor prefix for Safari */
  animation: slidein 120s forwards infinite alternate; /* Background animation */
}

/* Keyframes for the background animation */
@keyframes slidein {
  0%,
  100% {
    background-position: 20% 0%;
    background-size: 3400px;
  }
  50% {
    background-position: 100% 0%;
    background-size: 2400px;
  }
}

/* Styles for the album cover section */
.album-cover {
  width: 90%; /* Responsive width */
}

/* Styles for the Swiper container */
.swiper {
  width: 100%; /* Full width of its parent */
  padding: 40px 0 100px; /* Padding around the swiper */
}

/* Styles for each Swiper slide */
.swiper-slide {
  position: relative;
  max-width: 200px; /* Maximum width of each slide */
  aspect-ratio: 1/1; /* Keeps the slide square */
  border-radius: 10px; /* Rounded corners */
}

/* Styles for the images inside Swiper slides */
.swiper-slide img {
  object-fit: cover; /* Ensures the image covers the slide area */
  width: 100%; /* Full width of the slide */
  height: 100%; /* Full height of the slide */
  border-radius: inherit; /* Matches the border-radius of the slide */
  -webkit-box-reflect: below -5px linear-gradient(transparent, transparent, rgba(0, 0, 0, 0.4)); /* Reflect effect for the image */
  transform-origin: center; /* Sets the origin point for transformations */
  transform: perspective(800px); /* Applies perspective transformation */
  transition: 0.3s ease-out; /* Smooth transition for transformations */
  pointer-events: none; /* Disables pointer events on the image */
  user-select: none; /* Prevents text selection */
}

/* Styles for the overlay in the active Swiper slide */
.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); /* Dark overlay background */
  border-radius: inherit; /* Matches the border-radius of the slide */
  opacity: 0; /* Initially hidden */
  transition: all 0.4s linear; /* Smooth transition for opacity */
}

/* Show the overlay on hover */
.swiper-slide:hover .overlay {
  opacity: 1; /* Makes overlay visible */
}

/* Styles for the icon inside the overlay */
.swiper-slide .overlay ion-icon {
  opacity: 0; /* Initially hidden */
}

/* Styles for the icon when the slide is active and hovered */
.swiper-slide-active:hover .overlay ion-icon {
  font-size: 4rem; /* Larger icon size */
  color: #eb0b0b; /* Red color for the icon */
  opacity: 1; /* Makes icon visible */
  cursor: pointer; /* Pointer cursor on hover */
}

/* Music Player Styles */

/* Container for the music player */
.music-player {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: var(--primary-clr); /* Uses the primary color */
  width: 380px; /* Fixed width */
  padding: 10px 30px; /* Padding inside the player */
  border-radius: 20px; /* Rounded corners */
}

/* Title style inside the music player */
.music-player h1 {
  font-size: 1.5rem; /* Font size for the title */
  font-weight: 600; /* Font weight */
  line-height: 1.6; /* Line height for better readability */
}

/* Song name style inside the music player */
.music-player p {
  font-size: 1rem; /* Font size for the song name */
  font-weight: 400; /* Font weight */
  opacity: 0.6; /* Slightly transparent */
}

/* Styles for the progress slider */
#progress {
  appearance: none; /* Removes default styling */
  -webkit-appearance: none; /* Vendor prefix for WebKit browsers */
  width: 100%; /* Full width of the player */
  height: 7px; /* Height of the slider */
  background: rgba(163, 162, 164, 0.4); /* Light gray background */
  border-radius: 4px; /* Rounded corners */
  margin: 32px 0 24px; /* Margin above and below the slider */
  cursor: pointer; /* Pointer cursor on hover */
}

/* Styles for the slider thumb */
#progress::-webkit-slider-thumb {
  appearance: none; /* Removes default styling */
  -webkit-appearance: none; /* Vendor prefix for WebKit browsers */
  background: rgba(163, 162, 164, 0.9); /* Darker gray for the thumb */
  width: 16px; /* Width of the thumb */
  aspect-ratio: 1/1; /* Keeps the thumb square */
  border-radius: 50%; /* Circular thumb */
  outline: 4px solid var(--primary-clr); /* Outline with primary color */
  box-shadow: 0 6px 10px rgba(5, 36, 28, 0.3); /* Shadow effect */
}

/* Styles for the music player control buttons */
.controls {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Styles for each control button */
.controls button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px; /* Width of the button */
  aspect-ratio: 1/1; /* Keeps the button square */
  margin: 20px; /* Margin around the button */
  background: rgba(163, 162, 164, 0.3); /* Light gray background */
  color: var(--primary-clr); /* Primary color for the text */
  border-radius: 50%; /* Circular button */
  border: 1px solid rgba(255, 255, 255, 0.3); /* Light border */
  outline: 0; /* Removes default outline */
  font-size: 1.1rem; /* Font size for the icons */
  box-shadow: 0 10px 20px rgba(5, 36, 28, 0.3); /* Shadow effect */
  cursor: pointer; /* Pointer cursor on hover */
  transition: all 0.3s linear; /* Smooth transition for interactions */
}

/* Scales down buttons on hover or focus */
.controls button:is(:hover, :focus-visible) {
  transform: scale(0.96); /* Slightly scales down the button */
}

/* Special style for the play/pause button */
.controls button:nth-child(2) {
  transform: scale(1.3); /* Enlarges the play/pause button */
}

/* Scales down the play/pause button slightly on hover or focus */
.controls button:nth-child(2):is(:hover, :focus-visible) {
  transform: scale(1.25); /* Slightly scales down the button */
}

JavaScript Logic (script.js):

This JavaScript code is the engine behind a dynamic music player on a webpage. It acts as the brains, responding to user actions like playing, pausing, and switching between songs.

The code retrieves song information from a list and updates the player’s display to reflect the currently playing track. It uses carefully crafted functions to manage these actions and sets up event listeners to react to user clicks and interactions.

Furthermore, it seamlessly integrates with the Swiper library to create a visually appealing slider showcasing album covers, adding an extra layer of interactivity and enhancing the overall user experience.

// Get references to DOM elements
const progress = document.getElementById("progress"); // Progress slider for the audio
const song = document.getElementById("song"); // Audio element
const controlIcon = document.getElementById("controlIcon"); // Icon for play/pause button
const playPauseButton = document.querySelector(".play-pause-btn"); // Play/Pause button
const forwardButton = document.querySelector(".controls button.forward"); // Forward button
const backwardButton = document.querySelector(".controls button.backward"); // Backward button
const songName = document.querySelector(".music-player h1"); // Song title display
const artistName = document.querySelector(".music-player p"); // Artist name display

// Array of song objects with metadata
const songs = [
  {
    title: "Symphony",
    name: "Clean Bandit ft. Zara Larsson",
    source: "songs/Song1.mp3",
  },
  {
    title: "Pawn It All",
    name: "Alicia Keys",
    source: "songs/Song2.mp3",
  },
  {
    title: "Seni Dert Etmeler",
    name: "Madrigal",
    source: "songs/Song3.mp3",
  },
  {
    title: "Instant Crush",
    name: "Daft Punk ft. Julian Casablancas",
    source: "songs/Song4.mp3",
  },
  {
    title: "As It Was",
    name: "Harry Styles",
    source: "songs/Song5.mp3",
  },
  {
    title: "Physical",
    name: "Dua Lipa",
    source: "songs/Song6.mp3",
  },
  {
    title: "Delicate",
    name: "Taylor Swift",
    source: "songs/Song7.mp3",
  },
];

let currentSongIndex = 3; // Index of the currently playing song

// Function to update song information display
function updateSongInfo() {
  songName.textContent = songs[currentSongIndex].title; // Set the song title
  artistName.textContent = songs[currentSongIndex].name; // Set the artist name
  song.src = songs[currentSongIndex].source; // Set the audio source

  // Event listener for when the audio data is loaded
  song.addEventListener("loadeddata", function () {});
}

// Event listener to update the progress slider as the song plays
song.addEventListener("timeupdate", function () {
  if (!song.paused) {
    progress.value = song.currentTime; // Update slider value with current time
  }
});

// Event listener to set the maximum value of the progress slider and initialize it
song.addEventListener("loadedmetadata", function () {
  progress.max = song.duration; // Set slider maximum to song duration
  progress.value = song.currentTime; // Initialize slider value to current time
});

// Function to pause the song and update the play/pause icon
function pauseSong() {
  song.pause(); // Pause the audio
  controlIcon.classList.remove("fa-pause"); // Remove pause icon class
  controlIcon.classList.add("fa-play"); // Add play icon class
}

// Function to play the song and update the play/pause icon
function playSong() {
  song.play(); // Play the audio
  controlIcon.classList.add("fa-pause"); // Add pause icon class
  controlIcon.classList.remove("fa-play"); // Remove play icon class
}

// Function to toggle play/pause based on the current state
function playPause() {
  if (song.paused) {
    playSong(); // Play the song if it's paused
  } else {
    pauseSong(); // Pause the song if it's playing
  }
}

// Event listener for the play/pause button
playPauseButton.addEventListener("click", playPause);

// Event listener for the progress slider to update the song's current time
progress.addEventListener("input", function () {
  song.currentTime = progress.value; // Set song's current time to slider value
});

// Event listener for when the slider value is changed (e.g., after user interaction)
progress.addEventListener("change", function () {
  playSong(); // Play the song when the user changes the slider value
});

// Event listener for the forward button to skip to the next song
forwardButton.addEventListener("click", function () {
  currentSongIndex = (currentSongIndex + 1) % songs.length; // Move to the next song
  updateSongInfo(); // Update the song info display
  playPause(); // Play the next song
});

// Event listener for the backward button to go to the previous song
backwardButton.addEventListener("click", function () {
  currentSongIndex = (currentSongIndex - 1 + songs.length) % songs.length; // Move to the previous song
  updateSongInfo(); // Update the song info display
  playPause(); // Play the previous song
});

// Initialize the song info display
updateSongInfo();

// Initialize Swiper slider with coverflow effect
var swiper = new Swiper(".swiper", {
  effect: "coverflow", // Coverflow effect for the slider
  centeredSlides: true, // Center the current slide
  initialSlide: 3, // Start with the fourth slide
  slidesPerView: "auto", // Show multiple slides
  allowTouchMove: false, // Disable touch/swipe movement
  spaceBetween: 40, // Space between slides
  coverflowEffect: {
    rotate: 25, // Rotate effect for the slides
    stretch: 0, // No stretch effect
    depth: 50, // Depth of the coverflow effect
    modifier: 1, // Effect modifier
    slideShadows: false, // Disable slide shadows
  },
  navigation: {
    nextEl: ".forward", // Selector for the next slide button
    prevEl: ".backward", // Selector for the previous slide button
  },
});

Explanation of Code

  1. HTML Structure:
    • The HTML code sets up the basic structure of the music player, including the player controls, progress bar, and a container for the Swiper JS slider.
    • The swiper-wrapper will hold the song items dynamically added later.
  2. CSS Styling:
    • The CSS provides basic styling for the music player components, ensuring a clean and visually appealing layout.
    • Media queries are used to adjust the layout for different screen sizes, making the player responsive.
  3. JavaScript Logic:
    • Song Data: The songs array holds information about each song, including title and artist.
    • Swiper JS Initialization: The Swiper JS instance is initialized, configuring the slider’s behavior (number of slides per view, spacing, pagination, breakpoints).
    • Update Song Information: The updateSongInfo() function updates the song title and artist displayed in the player.
    • Play/Pause Functionality: The playPause() function toggles the playback state and updates the button text.
    • Previous/Next Song: The prevSong() and nextSong() functions handle navigation to the previous and next songs in the playlist, respectively.
    • Update Progress Bar: The updateProgressBar() function updates the progress bar width based on the current playback time.
    • Event Listeners: Event listeners are attached to the buttons and the music player to handle user interactions and updates.

Conclusion

This guide has provided a comprehensive framework for building a responsive music player with a slider feature using Swiper JS, HTML, CSS, and JavaScript. You can customize this project further by adding features like volume control, shuffle, repeat, and more. The responsiveness of the player ensures a seamless user experience across various devices. Remember to replace the placeholder song data with your own music library to create a fully functional music player.

How to Make a Responsive Music Player with Slider Using Swiper JS, HTML, CSS & JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top