86 lines
2.4 KiB
JavaScript
86 lines
2.4 KiB
JavaScript
const playlistEl = document.getElementById('playlist');
|
|
const audioPlayer = document.getElementById('audioPlayer');
|
|
const nextBtn = document.getElementById('nextBtn');
|
|
const prevBtn = document.getElementById('prevBtn');
|
|
|
|
let playlist = [];
|
|
let currentIndex = 0;
|
|
|
|
// Fetch the M3U playlist from the server
|
|
fetch('./playlist.m3u')
|
|
.then(res => {
|
|
if (!res.ok) throw new Error('Failed to load playlist.m3u');
|
|
return res.text();
|
|
})
|
|
.then(parseM3U)
|
|
.then(() => {
|
|
renderPlaylist();
|
|
loadTrack(0);
|
|
})
|
|
.catch(err => {
|
|
console.error(err);
|
|
playlistEl.innerHTML = '<li style="color:red;">Failed to load playlist.</li>';
|
|
});
|
|
|
|
function parseM3U(text) {
|
|
const lines = text.split('\n')
|
|
.map(line => line.trim())
|
|
.filter(line => line && !line.startsWith('#'));
|
|
playlist = lines;
|
|
}
|
|
|
|
function renderPlaylist() {
|
|
playlistEl.innerHTML = '';
|
|
playlist.forEach((path, index) => {
|
|
const li = document.createElement('li');
|
|
const a = document.createElement('a');
|
|
|
|
a.href = path; // make it a real link
|
|
a.textContent = path.split('/').pop();
|
|
a.target = "_blank"; // optional: opens in new tab if clicked normally
|
|
|
|
// Prevent default left-click navigation _ instead, play the song
|
|
a.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
loadTrack(index, true);
|
|
});
|
|
|
|
li.appendChild(a);
|
|
playlistEl.appendChild(li);
|
|
});
|
|
highlightActive();
|
|
}
|
|
|
|
function loadTrack(index, autoPlay = false) {
|
|
if (index < 0 || index >= playlist.length) return;
|
|
currentIndex = index;
|
|
audioPlayer.src = playlist[currentIndex];
|
|
highlightActive();
|
|
if (autoPlay) audioPlayer.play();
|
|
}
|
|
|
|
function highlightActive() {
|
|
Array.from(playlistEl.children).forEach((li, i) => {
|
|
li.classList.toggle('active', i === currentIndex);
|
|
});
|
|
}
|
|
|
|
// Controls
|
|
nextBtn.addEventListener('click', nextTrack);
|
|
prevBtn.addEventListener('click', prevTrack);
|
|
|
|
function nextTrack() {
|
|
if (currentIndex < playlist.length - 1) {
|
|
loadTrack(currentIndex + 1, true);
|
|
}
|
|
}
|
|
|
|
function prevTrack() {
|
|
if (currentIndex > 0) {
|
|
loadTrack(currentIndex - 1, true);
|
|
}
|
|
}
|
|
|
|
// Auto-play next song when one ends
|
|
audioPlayer.addEventListener('ended', nextTrack);
|