뮤직플레이어! 재생바와, 전으로 후로 어떻게 구현하지 ??
https://www.w3schools.com/tags/ref_av_dom.asp
HTML 요소로만 !
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;
//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();
}
playBtn.addEventListener("click", () => (isPlaying ? pauseSong() : playSong()));
prevBtn.addEventListener("click", prevSong);
nextBtn.addEventListener("click", nextSong);
music.addEventListener("ended", nextSong);
function loadSong(song) {
title.textContent = song.displayName;
artist.textContent = song.artist;
music.src = `./music/${song.name}.mp3`;
image.src = `./img/${song.name}.jpg`;
}
//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",
},
];
// 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();
}
music.addEventListener("timeupdate", updateProgressBar);
progressContainer.addEventListener("click", setProgressBar);
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}`;
}
}
function setProgressBar(e) {
const width = this.clientWidth;
const clickX = e.offsetX;
const { duration } = music;
music.currentTime = (clickX / width) * duration;
}
이 코드로, 키보드 이벤트추가하고, css custom 하면, 정말 나만의 오디오 플레이어를 만들 수 있겠다라는 생각이들었다!