JS Mini projects - Music Player

Seuling·2022년 6월 15일
0

FE

목록 보기
15/42
post-thumbnail

뮤직플레이어! 재생바와, 전으로 후로 어떻게 구현하지 ??

https://www.w3schools.com/tags/ref_av_dom.asp

💡 알게된 것

HTML 요소로만 !

JS

1. 초기셋팅

const music = document.querySelector("audio");
const prevBtn = document.getElementById("prev");
const playBtn = document.getElementById("play");
const nextBtn = document.getElementById("next");

//Check if Playing
let isPlaying = false;

2. Play기능, Pause기능 함수 생성

//Play
function playSong() {
  isPlaying = true;
  playBtn.classList.replace("fa-play", "fa-pause");
  playBtn.setAttribute("title", "Pause");
  music.play();
}

//Pause
function pauseSong() {
  isPlaying = false;
  playBtn.classList.replace("fa-pause", "fa-play");
  playBtn.setAttribute("title", "Play");
  music.pause();
}

3. Play or Pause Event Listenr

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

4. Update Dom

4-1. Event Listeners

prevBtn.addEventListener("click", prevSong);
nextBtn.addEventListener("click", nextSong);
music.addEventListener("ended", nextSong);

4-2. loadSong()함수 구현

function loadSong(song) {
  title.textContent = song.displayName;
  artist.textContent = song.artist;
  music.src = `./music/${song.name}.mp3`;
  image.src = `./img/${song.name}.jpg`;
}

4-3. songs 배열 생성

//mp3파일 저장이름과 name 동일해야함, 
const songs = [
  {
    name: "jacinto-1",
    displayName: "Electric Chill Machine",
    artist: "Sseul",
  },
  {
    name: "jacinto-2",
    displayName: "Seven Nation Army (Remix)",
    artist: "Sseul",
  },
  {
    name: "jacinto-3",
    displayName: "Goodnight, Disco Queen",
    artist: "Sseul",
  },
  {
    name: "metric-1",
    displayName: "Front Row (Remix)",
    artist: "Sseul",
  },
];

4-4. Current song, Previous Song, Next Song

// Current Song
let songIndex = 0;

// Previous Song
function prevSong() {
  songIndex--;
  if (songIndex < 0) {
    songIndex = songs.length - 1;
  }
  loadSong(songs[songIndex]);
  playSong();
}

// Next Song
function nextSong() {
  songIndex++;
  if (songIndex > songs.length - 1) {
    songIndex = 0;
  }
  loadSong(songs[songIndex]);
  playSong();
}

5. ProgressBar 구현

5-1. EventListeners

music.addEventListener("timeupdate", updateProgressBar);
progressContainer.addEventListener("click", setProgressBar);

5-2. updateProgressBar()

function updateProgressBar(e) {
  if (isPlaying) {
    const { duration, currentTime } = e.srcElement;
    // Update progress bar width
    const progressPercent = (currentTime / duration) * 100;
    progress.style.width = `${progressPercent}%`;
    // Caculate 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) {
      durationEl.textContent = `${durationMinutes}: ${durationSeconds}`;
    }
    // Caculate display for current
    const currentMinutes = Math.floor(currentTime / 60);
    let currentSeconds = Math.floor(currentTime % 60);
    if (currentSeconds < 10) {
      currentSeconds = `0${currentSeconds}`;
    }
    currentTimeEl.textContent = `${currentMinutes}: ${currentSeconds}`;
  }
}

5-3. setProgressBar()

function setProgressBar(e) {
  const width = this.clientWidth;
  const clickX = e.offsetX;
  const { duration } = music;
  music.currentTime = (clickX / width) * duration;
}

🤔 오늘의 생각

이 코드로, 키보드 이벤트추가하고, css custom 하면, 정말 나만의 오디오 플레이어를 만들 수 있겠다라는 생각이들었다!

profile
프론트엔드 개발자 항상 뭘 하고있는 슬링

0개의 댓글