[JavaScript] Custom Music Player

Background

The audio tag from HTML provides a default music player, or more specifically the browser provides a controllable music player for audio tags. However, since this is powered by the browser, customizing the player to fit the style and need of the web page is impossible. Therefore the alternative is to create a custom music player that is connected to the original audio source.

Code

HTML

<!-- hidden audio tag (with tachyon display-none class) -->
<audio class="media-player dn" src="{{ post.track_audio }}">mp3-preview</audio>

<!-- custom player -->
<div class="custom-player flex justify-around ph2 pv3 br3 items-center">
  <!-- play button -->
  <i class="fas fa-play action-btn pointer f4"></i>
  <!-- playing / duration -->
  <p>
    <span class="now-playing">0:00</span> / <span class="duration">0:30</span>
  </p>
  <!-- player bar -->
  <div class="stream-base h1 br-pill">
    <div class="stream-now h1 br-pill"></div>
  </div>
</div>

CSS

.custom-player {
  width: 20rem;
}

.stream-base {
  width: 10rem;
}

.stream-now {
  width: 0%;
}

JS

// Get default audio player, current play time, player bar
const player = document.querySelector(".media-player");
const nowPlaying = document.querySelector(".now-playing");
const playerBar = document.querySelector(".stream-now");

// Listener - whenever hidden audio time updates edit current time, player bar width
player.ontimeupdate = (e) => {
  const { currentTime, duration } = e.srcElement;
  playerBar.style.width = `${(currentTime / duration) * 100}%`;
  seconds = Math.floor(currentTime);
  if (seconds < 10) seconds = "0" + seconds;
  nowPlaying.innerHTML = "0:" + seconds;
};

// Get play button
const customBtn = document.querySelector(".action-btn");

// Listener - whenever action button is clicked play/pause audio source, toggle icon
customBtn.addEventListener("click", (e) => {
  if (e.target.classList.contains("fa-play")) {
    e.target.classList.remove("fa-play");
    e.target.classList.add("fa-pause");
    player.play();
  } else {
    e.target.classList.remove("fa-pause");
    e.target.classList.add("fa-play");
    player.pause();
  }
});