뮤직 플레이어

심민기·2022년 4월 30일
1

웹 개발

목록 보기
23/33
post-thumbnail

사이트 데모

강의

자바스크립트 분석.

음악 플레이

음악을 담는 배열.

const songs = [
  {
    name: 'jacinto-1',
    displayName: '아이스크림 협곡 대탐험!',
    artist: '녹차',
  },

내부적 이름과, 표현되는 이름, 작곡가명을 가지고 있다.

음악 실행하기.
플레이 버튼을 누를 때마다 실행과 멈춤이 일어나야 한다.

// Play or Pause Event Listener
playBtn.addEventListener('click', () => (isPlaying ? pauseSong() : playSong()));
이렇게 클릭 이벤트로 실행하자.

playsong을 보면.

// 음악이 실행되는가??
let isPlaying = false;


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

음악이 실행되는 지를 확인.
버튼을 멈춤상태로 바꿈.
음악을 실행.
function pauseSong()은 이거와 정반대로 실행한다.

다음곡, 이전곡

// 현재 곡
let songIndex = 0;

//맨처음 로드시에 첫곡연주.
loadSong(songs[songIndex]);

이후에는 prev,next버튼을 눌러 곡을 변경한다.

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

이전곡으로 넘어가기 위해 배열을 하나 넘어가고. 맨처음에서 맨뒤로 넘어가며 load와 play를 실행.

load는

// DOM 문서를 업데이트
function loadSong(song) {
  title.textContent = song.displayName;
  artist.textContent = song.artist;
  music.src = `music/${song.name}.mp3`;
  image.src = `img/${song.name}.jpg`;
}

곡이 바뀔 떄마다 곡이름, 커버이미지. 아티스트 명, 시간등을 바꿔주는 것은 loadsong.

진행바.

진행률바를 표현하자.

진행을 표시하는 두개의 이벤트

music.addEventListener('timeupdate', updateProgressBar);
음악이 매초마다 업데이트 실행.
progressContainer.addEventListener('click', setProgressBar);

자동으로 진행되는 진행률

//맨처음 로드시에 첫곡연주.
loadSong(songs[songIndex]);

// Update Progress Bar & Time
function updateProgressBar(e) {
  if (isPlaying) {
    const { duration, currentTime } = e.srcElement;
    //노래의 전체길이, 현재시간을 객체로서 전달받는다. (구조분해할당.)

    // 진행바 길이 업데이트
    const progressPercent = (currentTime / duration) * 100;
    progress.style.width = `${progressPercent}%`;
    //퍼센티지로 표현.

    // 노래의 전체 시간(2:0x)을 계산하기.
    const durationMinutes = Math.floor(duration / 60);
    let durationSeconds = Math.floor(duration % 60);
    if (durationSeconds < 10) {
      durationSeconds = `0${durationSeconds}`;
    }
    //초가 10초 미만이명 0X 이런형식으로 표현하기.

    // 그냥 표기하면 일순간 분초가 NAN으로 표시된다. 정보를 전달받는 첫과정이 실행되지 못해 값이 없는 것. 이걸 해결하기 위해 조건문 사용.    
    if (durationSeconds) {
      durationEl.textContent = `${durationMinutes}:${durationSeconds}`;
    }//초가 있어야만 시간이 표기된다.

    // 현재 시간을 계산.
    const currentMinutes = Math.floor(currentTime / 60);
    let currentSeconds = Math.floor(currentTime % 60);
    if (currentSeconds < 10) {
      currentSeconds = `0${currentSeconds}`;
    }
    currentTimeEl.textContent = `${currentMinutes}:${currentSeconds}`;
  }
}

마우스 클릭으로 진행률 설정.
progressContainer.addEventListener('click', setProgressBar);

// 진행률 바 설정.
function setProgressBar(e) {
  const width = this.clientWidth;
  const clickX = e.offsetX;
  //진행률바의 길이와 음악의 진행률을 .
  const { duration } = music;
  music.currentTime = (clickX / width) * duration;
}

music.currentTime = (clickX / width) * duration;
클릭 위치 / 진행바의 길이를 음악의 길이로 나누면, 클릭한 만큼의 음악 진행이되고 이를 음악의 현재시간에 저장함으로 마우스클릭으로 진행을 변경하게 한다.

currentTime은 현재 시간을 초단위로 받음.
currentTime

img,music폴더를 만들어서 한번 넣어보자!

profile
왕초보

0개의 댓글