-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
171 lines (141 loc) · 5.55 KB
/
index.js
File metadata and controls
171 lines (141 loc) · 5.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
const image = document.getElementById('cover'),
title = document.getElementById('music-title'),
artist = document.getElementById('music-artist'),
currentTimeEl = document.getElementById('current-time'),
durationEl = document.getElementById('duration'),
progress = document.getElementById('progress'),
playerProgress = document.getElementById('player-progress'),
prevBtn = document.getElementById('prev'),
nextBtn = document.getElementById('next'),
playBtn = document.getElementById('play'),
background = document.getElementById('bg-img');
const music = new Audio();
let musicIndex = 1;
let isPlaying = false;
let artists = {};
let songName = {};
async function initPlayer() {
try {
const response = await fetch('./data.json');
if (!response.ok) throw new Error('Failed to load data.json');
const data = await response.json();
artists = data.artist || {};
songName = data.songName || {};
await loadMusic(musicIndex);
enableControls();
} catch (error) {
console.error("Player initialization error:", error);
showErrorState();
loadMusic(musicIndex);
}
}
function enableControls() {
[prevBtn, nextBtn, playBtn, playerProgress].forEach(el => {
el.style.opacity = '1';
el.style.pointerEvents = 'auto';
});
}
function showErrorState() {
title.textContent = "Player Error";
artist.textContent = "Check console for details";
console.error("Using fallback mode - some features may not work");
}
function togglePlay() {
if (music.src) {
isPlaying ? pauseMusic() : playMusic();
}
}
async function playMusic() {
try {
await music.play();
isPlaying = true;
playBtn.classList.replace('fa-play', 'fa-pause');
playBtn.setAttribute('title', 'Pause');
} catch (err) {
console.error("Playback failed:", err);
isPlaying = false;
}
}
function pauseMusic() {
music.pause();
isPlaying = false;
playBtn.classList.replace('fa-pause', 'fa-play');
playBtn.setAttribute('title', 'Play');
}
async function loadMusic(index) {
const audioPath = `assets/song/${index}.mp3`;
const coverPath = `assets/image/${index}.jpg`;
try {
const [audioCheck, coverCheck] = await Promise.all([
fetch(audioPath, { method: 'HEAD' }),
fetch(coverPath, { method: 'HEAD' })
]);
if (!audioCheck.ok || !coverCheck.ok) {
throw new Error('Audio or cover not found');
}
music.src = audioPath;
image.src = coverPath;
background.src = coverPath;
title.textContent = songName[index] || `Track ${index}`;
artist.textContent = artists[index] || "Unknown Artist";
if (isPlaying) {
await playMusic();
}
music.addEventListener('loadedmetadata', () => {
updateProgressBar();
});
} catch (error) {
console.error(`Error loading track ${index}:`, error);
handleTrackLoadError(index);
}
}
function handleTrackLoadError(currentIndex) {
if (currentIndex > 1) {
musicIndex = currentIndex - 1;
} else {
musicIndex = currentIndex + 1;
}
if (musicIndex > 20 || musicIndex < 1) {
musicIndex = 1;
showErrorState();
return;
}
loadMusic(musicIndex);
}
function changeMusic(direction) {
musicIndex += direction;
let nextAudio = new Audio(`assets/song/${musicIndex}.mp3`);
nextAudio.onerror = () => {
musicIndex = 1;
loadMusic(musicIndex);
playMusic();
};
loadMusic(musicIndex);
playMusic();
}
function updateProgressBar() {
const { duration, currentTime } = music;
const progressPercent = (currentTime / duration) * 100;
progress.style.width = `${progressPercent}%`;
const formatTime = (time) => {
if (isNaN(time)) return "0:00";
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
};
durationEl.textContent = formatTime(duration);
currentTimeEl.textContent = formatTime(currentTime);
}
function setProgressBar(e) {
if (!music.src) return;
const width = playerProgress.clientWidth;
const clickX = e.offsetX;
music.currentTime = (clickX / width) * music.duration;
}
playBtn.addEventListener('click', togglePlay);
prevBtn.addEventListener('click', () => changeMusic(-1));
nextBtn.addEventListener('click', () => changeMusic(1));
music.addEventListener('ended', () => changeMusic(1));
music.addEventListener('timeupdate', updateProgressBar);
playerProgress.addEventListener('click', setProgressBar);
document.addEventListener('DOMContentLoaded', initPlayer);