Music Player With Javascript

Music Player With Javascript

Functional Music Player with html , css , javascript

Welcome to another exciting project in our 30 Project Webdev Series! Today, we'll be diving into the world of interactivity by creating a simple yet functional music player using HTML, CSS, and JavaScript. This project serves as a great introduction to building dynamic web experiences with code.

Introduction

Music is an integral part of many lives. Whether you're working out, relaxing, or simply enjoying your commute, having access to your favorite tunes can significantly enhance the experience. However, relying solely on dedicated music apps isn't always convenient. This is where a web-based music player comes in. By building your own, you gain control over the functionality and aesthetics, making it a personalized music companion.

Project Structure

Our music player will consist of three main components:

  1. HTML Structure: This forms the foundation of our player, defining the visual layout and incorporating the audio element.

  2. CSS Styling: We'll use CSS to style the player's appearance, making it visually appealing and user-friendly.

  3. JavaScript Logic: Here's where the magic happens! JavaScript code will add interactivity, allowing users to play, pause, adjust volume, and potentially navigate between songs.

Step 1: Building the HTML Structure

Let's begin by creating an HTML file named music-player.html. Here's the basic structure:

HTML

<body>
    <div class="music-container">
      <div class="music-body">
        <div class="music-info">
          <h2 id="title">Yıldız Tozu</h2>
        </div>
        <audio
          src="https://raw.githubusercontent.com/ustabasiibrahim/music-player/master/assets/music/1.mp3"
          id="audio"
        ></audio>
        <div class="music-progress">
          <div class="progress-bar">
            <span class="progress-line"></span>
            <input
              type="range"
              min="0"
              max="100"
              value="0"
              class="progress"
              id="progress"
            />
          </div>
          <div class="duration">
            <span class="current-time">00:00</span>
            <span class="duration-time">00:00</span>
          </div>
        </div>
        <div class="music-controls">
          <button class="repeat btn" id="repeat">
            <i class="fas fa-redo-alt"></i>
          </button>
          <div class="main-controls">
            <button class="playpause" id="playpause">
              <i id="playpause-btn" class="fas fa-play"></i>
            </button>
          </div>
          <button class="like btn" id="like">
            <i id="likeicon" class="far fa-heart"></i>
          </button>
        </div>
        <div class="songs-list" id="songs-list">
          <button class="list-close btn" id="listclose">
            <i class="fas fa-times"></i>
          </button>
        </div>
      </div>
    </div>
  </body>

Step 2: Styling with CSS

Create a CSS file named style.css and add the following styles:

CSS

@import url('https://fonts.googleapis.com/css2?family=Lato&display=swap');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Lato', sans-serif;
    background-color: #0762f5;
}

.music-container {
    width: 100%;
    min-height: 100vh;
    display: grid;
    place-items: center;
}

.music-body {
    box-shadow: 0 20px 50px #3d11839f;
    background: #fff;
    padding: 1.3rem;
    border-radius: 1.5rem;
    position: relative;
    overflow: hidden;
}

.btn {
    outline: none;
    border: 0;
    background: #eee6fc;
    font-size: 0.9rem;
    color: #0762f5;
    height: 2.188rem;
    width: 2.188rem;
    border-radius: 50%;
    cursor: pointer;
}





.volume-slider,
.progress-bar {
    position: relative;
    width: 100%;
    height: 0.2rem;
    background: #eee6fc;
}

.volume-slider {
    width: 80%;
}

.volume-slider {
    right: -15px;
    ;
}

.volume-slider .bar,
.progress-bar .progress-line {
    display: block;
    width: 0;
    height: inherit;
    background-color: #0762f5;
}

.volume-slider .bar {
    width: 100%;
}

.volume-slider .volumerange,
.progress-bar .progress {
    width: 100%;
    -webkit-appearance: none;
    height: inherit;
    background: transparent;
    outline: none;
    position: absolute;
    top: 0;
    left: 0;
}

.volume-slider .volumerange::-webkit-slider-thumb,
.progress-bar .progress::-webkit-slider-thumb {
    -webkit-appearance: none;
    height: 0.7rem;
    width: 0.7rem;
    background-color: #0762f5;
    border-radius: 50%;
    cursor: pointer;
}

/* volume range slider design end */




.music-info {
    text-align: center;
}

.music-info h2 {
    font-size: 1rem;
    margin-top: 1rem;
    letter-spacing: 0.02rem;
    color: rgb(117, 116, 116);
    color: #0762f5;
}

.music-progress {
    margin-top: 1rem;
}

.music-progress .progress-bar {
    background: #ebdfff;
    height: 0.2rem;
    width: 100%;
    margin-bottom: 0.4rem;
    position: relative;
}

.progress-bar {
    cursor: pointer;
}

.progress {
    background: #0762f5;
    width: 0;
    height: 100%;
    position: relative;
}

.progress::before {
    content: "";
    position: absolute;
    height: 0.7rem;
    width: 0.7rem;
    border-radius: 50%;
    top: 50%;
    right: -5px;
    z-index: 2;
    transform: translateY(-50%);
    background: inherit;
    transition: all 0.1s ease;
}

.duration {
    display: flex;
    color: #0762f5;
    justify-content: space-between;
}

.duration span {
    font-size: 0.7rem;
}

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


.playpause {
    border: 0;
    outline: 0;
    font-size: 2rem;
    background: #fff;
    color: #0762f5;
    cursor: pointer;
}

.prevbtn:hover,
.nextbtn:hover {
    color: #5717be;
}


.playpause {
    font-size: 1.7rem;
    /* position: absolute; */
    background: #0762f5;
    height: 4.5rem;
    width: 4.5rem;
    color: #fff;
    border-radius: 50%;
    display: grid;
    place-items: center;
}

.fa-play {
    position: relative;
    display: inline-block;
    left: 0.1rem;
}



.main-controls {
    position: relative;
    /* border: 1px solid #b88ffa; */
    border-radius: 2rem;
    padding: 0.5rem 1rem;
    display: flex;
    justify-content: space-between;
    gap: 1.3rem;
}

.color {
    color: #9db3fa;
}

Step 3: Adding Programming Logic with JavaScript

Create a JavaScript file named script.js and add the following code:

JavaScript


  const playPause = document.querySelector("#playpause");
  const playPauseBtn = document.querySelector("#playpause-btn");
  const audio = document.querySelector("#audio");
  const title = document.querySelector("#title");
  const progress = document.querySelector("#progress");
  const progressBar = document.querySelector(".progress-bar");
  const currTime = document.querySelector(".current-time");
  const totalDuration = document.querySelector(".duration-time");
  const progressLine = document.querySelector(".progress-line");
  const repeatBtn = document.querySelector("#repeat");
  const likeBtn = document.querySelector("#like");
  const likeIcon = document.querySelector("#likeicon");
  // songs array

  const songs = [
    {
      path: "https://raw.githubusercontent.com/ustabasiibrahim/music-player/master/assets/music/1.mp3",
      displayName: "Yıldız Tozu",
      artist: "Ozbi",
      cover:
        "https://images.genius.com/ee202c6f724ffd4cf61bd01a205eeb47.1000x1000x1.jpg",
    },
  ];

  // deafult song index

  let songIndex = 2;

  // song default state

  let isPlaying = false;

  // song pause function

  function playSong() {
    isPlaying = true;
    playPauseBtn.classList.replace("fa-play", "fa-pause");
    audio.play();
  }

  // song play function

  function pauseSong() {
    isPlaying = false;
    playPauseBtn.classList.replace("fa-pause", "fa-play");
    audio.pause();
  }

  // progress bar function
  console.log(audio.duration);

  function updateProgress(e) {
    if (isPlaying) {
      const { duration, currentTime } = e.target;
      // Update progress bar width
      const progressPercent = (currentTime / duration) * 100;
      progress.value = progressPercent;
      progressLine.style.width = `${progressPercent}%`;
      if (progressPercent == 100) {
        return nextSong();
      }
      // Calculate display for duration
      const durationMinutes = Math.floor(duration / 60);
      let durationSeconds = Math.floor(duration % 60);
      if (durationSeconds < 10) {
        durationSeconds = `0${durationSeconds}`;
      }
      // Delay switching duration Element to avoid NaN
      if (durationSeconds) {
        totalDuration.textContent = `${durationMinutes}:${durationSeconds}`;
      }
      // Calculate display for currentTime
      let currentMinutes = Math.floor(currentTime / 60);
      let currentSeconds = Math.floor(currentTime % 60);
      if (currentSeconds < 10) {
        currentSeconds = `0${currentSeconds}`;
      }
      currTime.textContent = `${currentMinutes}:${currentSeconds}`;
    }
  }

  function progressSlide(e) {
    const { value } = e.target;
    const progressTime = Math.ceil((audio.duration / 100) * value);
    audio.currentTime = progressTime;
    console.log(progressTime);
    if (!isPlaying) {
      progressLine.style.width = `${value}%`;
    }
  }

  function repeat() {
    repeatBtn.classList.toggle("color");
    const repeatBtnState = repeatBtn.classList.contains("color");
    if (repeatBtnState) {
      audio.loop = true;
      loadSong();
    } else {
      audio.loop = false;
      loadSong();
    }
  }

  function like() {
    if (likeBtn.classList.toggle("color")) {
      likeIcon.classList.replace("far", "fas");
    } else {
      likeIcon.classList.replace("fas", "far");
    }
  }

  playPause.addEventListener("click", () =>
    isPlaying ? pauseSong() : playSong()
  );

  audio.addEventListener("timeupdate", updateProgress);
  progress.addEventListener("input", progressSlide);
  repeatBtn.addEventListener("click", repeat);
  likeBtn.addEventListener("click", like);

Step 4: Testing and Customization

Save all your files (music-player.html, style.css, and script.js) in the same directory and open the music-player.html file in your web browser. You should see a basic music player with a title, play/pause button, and volume slider. Click the button to play/pause the audio and adjust the slider to control the volume.

Customization:

  • Feel free to customize the appearance further using CSS. You can style the buttons, adjust font sizes and colors, and add background images or gradients.

  • Explore adding features like a progress bar that displays the current playback position within the song.

  • Consider incorporating playlists by allowing users to choose from multiple songs.

Output:

Click here to view source code

Conclusion

Congratulations! You've successfully built a functional music player using HTML, CSS, and JavaScript. This project serves as a stepping stone to explore more complex web interactions and user interfaces. As you continue your web development journey, remember to experiment, explore new libraries and frameworks, and keep building cool projects!

FAQ

1. What audio formats can I use?

While MP3 is widely supported, you can also explore using formats like Ogg Vorbis (.ogg) or WAV (.wav). However, browser compatibility might vary for these formats.

2. Can I add a playlist functionality?

Absolutely! You can create an interface that allows users to choose from multiple songs stored in different audio files. Update the src attribute of the audio element based on user selection to switch between songs.

3. How can I display the current playback time?

You can utilize the player.currentTime property in JavaScript to retrieve the current playback position in seconds. Update a progress bar element dynamically based on this value to provide a visual representation of the song's progress.

4. Can I add functionalities like rewind and fast-forward?

Yes! You can explore using the player.currentTime property to set the playback position to a specific point in the song, allowing users to rewind or fast-forward.

5. How can I make the player more responsive for different screen sizes?

Utilize media queries in your CSS to adjust the layout and styling based on the screen size. This ensures your music player looks good and functions well across various devices


I hope this blog post empowers you to build your own music player and take your web development skills to the next level. Happy coding!