Sharing is caring!

JavaScript project: Music Player

Steps

  1. Define an array of song objects, where each object contains information about a song, such as its title, artist, album, and file path.
  2. Create a function that initializes the music player by setting up the necessary HTML elements and event listeners. This function should also load the first song in the array and display its information in the player.
  3. Create functions to handle playing, pausing, and skipping tracks. These functions should update the HTML elements to reflect the current song and play or pause the audio file.
  4. Create functions to handle the progress bar and current time display. These functions should update the progress bar and current time as the song plays.
  5. Create functions to handle user interactions with the music player, such as clicking on the play/pause button or clicking on a song in the playlist.
  6. Add styling to make the music player look visually appealing and user-friendly.

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Music Player</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1>Music Player</h1>
    <audio id="audio-player"></audio>
    <div id="song-info">
      <h2 id="song-title"></h2>
      <h3 id="song-artist"></h3>
      <h3 id="song-album"></h3>
    </div>
    <div id="player-controls">
      <button id="play-pause-btn"><i class="fas fa-play"></i></button>
      <button id="skip-back-btn"><i class="fas fa-backward"></i></button>
      <button id="skip-forward-btn"><i class="fas fa-forward"></i></button>
      <div id="time-info">
        <span id="current-time">0:00</span>
        <span>/</span>
        <span id="duration">0:00</span>
      </div>
      <div id="progress-bar-container">
        <div id="progress-bar"></div>
      </div>
    </div>
    <ul id="song-list"></ul>
    <script src="app.js"></script>
  </body>
</html>

CSS

/* Add CSS styling for the Music Player interface */

body {
  background-color: #333;
  color: #fff;
  font-family: sans-serif;
  margin: 0;
  padding: 0;
}

h1, h2, h3 {
  margin: 0;
  padding: 10px;
}

#audio-player {
  display: none;
}

#song-info {
  text-align: center;
}

#player-controls {
  align-items: center;
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

#player-controls button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  font-size: 1.5em;
  margin: 0 10px;
  outline: none;
}

#player-controls button i {
  color: white;
}

#time-info {
  color: white;
  font-size: 0.8em;
  margin: 0 10px;
}

#progress-bar-container {
  background-color: #ccc;
  height: 5px;
  margin: 10px;
  width: 80%;
}

#progress-bar {
  background-color: #fff;
  height: 100%;
  width: 0%;
  transition: width 0.1s linear;
}

#song-list {
  list-style: none;
  margin: 20px 0;
  padding: 0;
}

#song-list li {
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  cursor: pointer;
  margin: 5px;
  padding: 10px;
}

#song-list li:hover {
  background-color: #ddd;
}

#song-list li.active {
  background-color: #ddd;
}

JavaScript

// Define the audio player and song list variables
const audioPlayer = document.getElementById("audio-player");
const songList = document.getElementById("song-list");

// Define the current song and index variables
let currentSong = null;
let currentIndex = 0;

// Define the play button variable and add an event listener to it
const playButton = document.getElementById("play");
playButton.addEventListener("click", togglePlay);

// Define the previous and next button variables and add event listeners to them
const prevButton = document.getElementById("prev");
prevButton.addEventListener("click", playPrevSong);

const nextButton = document.getElementById("next");
nextButton.addEventListener("click", playNextSong);

// Define the progress bar and time info variables
const progressBar = document.getElementById("progress-bar");
const timeInfo = document.getElementById("time-info");

// Define the song list items and add event listeners to them
const songItems = songList.getElementsByTagName("li");
for (let i = 0; i < songItems.length; i++) {
  songItems[i].addEventListener("click", function() {
    playSong(i);
  });
}

// Initialize the audio player
audioPlayer.src = songItems[0].getAttribute("data-src");
audioPlayer.load();

// Function to play a song
function playSong(index) {
  // Set the current song and index variables
  currentSong = songItems[index];
  currentIndex = index;

  // Update the song info display
  const songTitle = currentSong.getElementsByTagName("span")[0].textContent;
  const songArtist = currentSong.getElementsByTagName("span")[1].textContent;
  document.getElementById("song-title").textContent = songTitle;
  document.getElementById("song-artist").textContent = songArtist;

  // Update the active class on the song list items
  for (let i = 0; i < songItems.length; i++) {
    songItems[i].classList.remove("active");
  }
  currentSong.classList.add("active");

  // Load and play the selected song
  audioPlayer.src = currentSong.getAttribute("data-src");
  audioPlayer.play();

  // Update the play button icon
  playButton.innerHTML = "<i class='fas fa-pause'></i>";
}

// Function to toggle the play/pause state of the audio player
function togglePlay() {
  if (audioPlayer.paused) {
    audioPlayer.play();
    playButton.innerHTML = "<i class='fas fa-pause'></i>";
  } else {
    audioPlayer.pause();
    playButton.innerHTML = "<i class='fas fa-play'></i>";
  }
}

// Function to play the previous song
function playPrevSong() {
  if (currentIndex === 0) {
    playSong(songItems.length - 1);
  } else {
    playSong(currentIndex - 1);
  }
}

// Function to play the next song
function playNextSong() {
  if (currentIndex === songItems.length - 1) {
    playSong(0);
  } else {
    playSong(currentIndex + 1);
  }
}

// Event listener to update the progress bar and time info as the song plays
audioPlayer.addEventListener("timeupdate", function() {
  const duration = audioPlayer.duration;
  const currentTime = audioPlayer.currentTime;
  const progress = (currentTime / duration) * 100;
  progressBar.style.width = progress + "%";
  timeInfo.textContent = formatTime(currentTime) + " / " + formatTime(duration);
});
// Function to format the time in minutes and seconds
function formatTime(time) {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
}
// Function to initialize the music player
function initializePlayer() {
  // Get references to the DOM elements
  const audioElement = document.getElementById("audio");
  const playButton = document.getElementById("play-button");
  const pauseButton = document.getElementById("pause-button");
  const nextButton = document.getElementById("next-button");
  const previousButton = document.getElementById("previous-button");
  const progressBar = document.getElementById("progress-bar");
  const currentTime = document.getElementById("current-time");
  const totalTime = document.getElementById("total-time");

  // Set up the initial state of the player
  let currentTrackIndex = 0;
  let isPlaying = false;
  let tracks = [
    {
      title: "Track 1",
      artist: "Artist 1",
      album: "Album 1",
      url: "path/to/track1.mp3",
      duration: 180,
    },
    {
      title: "Track 2",
      artist: "Artist 2",
      album: "Album 2",
      url: "path/to/track2.mp3",
      duration: 240,
    },
    {
      title: "Track 3",
      artist: "Artist 3",
      album: "Album 3",
      url: "path/to/track3.mp3",
      duration: 210,
    },
  ];

  // Load the first track into the audio element
  audioElement.src = tracks[currentTrackIndex].url;

  // Update the current time and total time displays
  currentTime.textContent = formatTime(audioElement.currentTime);
  totalTime.textContent = formatTime(tracks[currentTrackIndex].duration);

  // Add event listeners to the buttons
  playButton.addEventListener("click", () => {
    isPlaying = true;
    audioElement.play();
    playButton.style.display = "none";
    pauseButton.style.display = "inline-block";
  });

  pauseButton.addEventListener("click", () => {
    isPlaying = false;
    audioElement.pause();
    pauseButton.style.display = "none";
    playButton.style.display = "inline-block";
  });

  nextButton.addEventListener("click", () => {
    if (currentTrackIndex < tracks.length - 1) {
      currentTrackIndex++;
      audioElement.src = tracks[currentTrackIndex].url;
      audioElement.play();
      playButton.style.display = "none";
      pauseButton.style.display = "inline-block";
      currentTime.textContent = formatTime(audioElement.currentTime);
      totalTime.textContent = formatTime(tracks[currentTrackIndex].duration);
    }
  });

  previousButton.addEventListener("click", () => {
    if (currentTrackIndex > 0) {
      currentTrackIndex--;
      audioElement.src = tracks[currentTrackIndex].url;
      audioElement.play();
      playButton.style.display = "none";
      pauseButton.style.display = "inline-block";
      currentTime.textContent = formatTime(audioElement.currentTime);
      totalTime.textContent = formatTime(tracks[currentTrackIndex].duration);
    }
  });

  // Add an event listener to the audio element to update the current time display
  audioElement.addEventListener("timeupdate", () => {
    currentTime.textContent = formatTime(audioElement.currentTime);
    progressBar.value = audioElement.currentTime;
  });

  // Add an event listener to the progress bar to allow seeking
  progressBar.addEventListener("input", () => {
    audioElement.currentTime = progressBar.value;
    currentTime.textContent = formatTime(audioElement.currentTime);
  });
}


12 Comments

Asianssnozy · June 28, 2023 at 9:33 pm

Hello guys! Nice article

GLORY_hmKn · July 25, 2023 at 12:29 am

its very good

Technology_fuki · August 3, 2023 at 7:10 pm

good

Product_owpr · August 7, 2023 at 6:50 am

thank you brooooo

Eco_owsn · August 11, 2023 at 9:37 pm

thank you

Timothylit · September 21, 2023 at 12:08 am

interesting

DavidCrarm · September 29, 2023 at 2:45 am

nothing special

winline_crSn · September 30, 2023 at 5:13 pm

Thank you it is a good one

home_mcOi · November 29, 2023 at 11:24 am

good

impact_lhKi · November 30, 2023 at 6:30 pm

thank you

Esbetit · March 14, 2024 at 6:55 pm

Cool + for the post

Registrácia na binance · March 31, 2024 at 2:22 am

Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

Leave a Reply

Avatar placeholder

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

Cheap flights with cashback