No song selected
#music-player {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
background: #222;
color: white;
z-index: 1000;
}
#playlist {
margin-bottom: 70px;
}
#playlist li {
cursor: pointer;
padding: 6px;
}
#playlist li.active {
font-weight: bold;
color: #4dc3ff;
}
const songs = [
{
title: "First Song",
file: "/music/first-song.mp3"
},
{
title: "Second Song",
file: "/music/second-song.mp3"
},
{
title: "Third Song",
file: "/music/third-song.mp3"
}
];
const audio = document.querySelector("#audio");
const playButton = document.querySelector("#play");
const previousButton = document.querySelector("#previous");
const nextButton = document.querySelector("#next");
const volumeControl = document.querySelector("#volume");
const songTitle = document.querySelector("#song-title");
const playlist = document.querySelector("#playlist");
let currentSong = Number(localStorage.getItem("currentSong")) || 0;
function renderPlaylist() {
playlist.innerHTML = "";
songs.forEach((song, index) => {
const item = document.createElement("li");
item.textContent = song.title;
item.addEventListener("click", () => loadSong(index, true));
playlist.appendChild(item);
});
}
function updatePlaylistHighlight() {
[...playlist.children].forEach((item, index) => {
item.classList.toggle("active", index === currentSong);
});
}
function loadSong(index, shouldPlay = false) {
currentSong = index;
audio.src = songs[currentSong].file;
songTitle.textContent = songs[currentSong].title;
localStorage.setItem("currentSong", currentSong);
updatePlaylistHighlight();
if (shouldPlay) {
audio.play()
.then(() => {
playButton.textContent = "⏸";
})
.catch(() => {
// The browser may require a user interaction first.
});
}
}
playButton.addEventListener("click", () => {
if (audio.paused) {
audio.play();
playButton.textContent = "⏸";
} else {
audio.pause();
playButton.textContent = "▶";
}
});
previousButton.addEventListener("click", () => {
loadSong((currentSong - 1 + songs.length) % songs.length, true);
});
nextButton.addEventListener("click", () => {
loadSong((currentSong + 1) % songs.length, true);
});
audio.addEventListener("ended", () => {
loadSong((currentSong + 1) % songs.length, true);
});
volumeControl.addEventListener("input", () => {
audio.volume = volumeControl.value;
localStorage.setItem("volume", volumeControl.value);
});
audio.volume = Number(localStorage.getItem("volume")) || 0.8;
renderPlaylist();
loadSong(currentSong);