-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
311 lines (262 loc) · 9.09 KB
/
main.js
File metadata and controls
311 lines (262 loc) · 9.09 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Audio Context for visualizer
let audioContext;
let analyser;
let source;
// Demo playlist data
const demoPlaylist = [
{
id: 1,
title: "Song 1",
artist: "Artist 1",
url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
artwork: "https://placehold.co/300x300/1976d2/ffffff?text=Song+1"
},
{
id: 2,
title: "Song 2",
artist: "Artist 2",
url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",
artwork: "https://placehold.co/300x300/2196f3/ffffff?text=Song+2"
},
{
id: 3,
title: "Song 3",
artist: "Artist 3",
url: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3",
artwork: "https://placehold.co/300x300/64b5f6/ffffff?text=Song+3"
}
];
class MusicPlayer {
constructor() {
this.audio = new Audio();
this.playlist = [];
this.currentTrackIndex = 0;
this.isPlaying = false;
this.isShuffled = false;
this.repeatMode = 'none'; // none, one, all
}
initializePlayer() {
// Initialize audio context for visualizer
this.initializeAudioContext();
// Load playlist from localStorage or use demo playlist
this.loadPlaylist();
// Initialize UI elements
this.initializeUI();
// Setup event listeners
this.setupEventListeners();
// Initialize visualizer
this.setupVisualizer();
}
initializeAudioContext() {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
source = audioContext.createMediaElementSource(this.audio);
source.connect(analyser);
analyser.connect(audioContext.destination);
}
loadPlaylist() {
const savedPlaylist = localStorage.getItem('musicPlayerPlaylist');
this.playlist = savedPlaylist ? JSON.parse(savedPlaylist) : demoPlaylist;
this.renderPlaylist();
}
initializeUI() {
// Get UI elements
this.elements = {
playBtn: document.getElementById('play'),
prevBtn: document.getElementById('prev'),
nextBtn: document.getElementById('next'),
shuffleBtn: document.getElementById('shuffle'),
repeatBtn: document.getElementById('repeat'),
muteBtn: document.getElementById('mute'),
progress: document.getElementById('progress'),
progressContainer: document.querySelector('.progress-bar'),
volumeBar: document.querySelector('.volume-bar'),
volumeProgress: document.querySelector('.volume-progress'),
currentTime: document.getElementById('current-time'),
duration: document.getElementById('duration'),
albumArt: document.getElementById('album-art'),
trackTitle: document.getElementById('track-title'),
trackArtist: document.getElementById('track-artist'),
playlistContainer: document.getElementById('playlist'),
visualizer: document.getElementById('visualizer')
};
}
setupEventListeners() {
// Playback controls
this.elements.playBtn.addEventListener('click', () => this.togglePlay());
this.elements.prevBtn.addEventListener('click', () => this.prevTrack());
this.elements.nextBtn.addEventListener('click', () => this.nextTrack());
this.elements.shuffleBtn.addEventListener('click', () => this.toggleShuffle());
this.elements.repeatBtn.addEventListener('click', () => this.toggleRepeat());
this.elements.muteBtn.addEventListener('click', () => this.toggleMute());
// Progress bar
this.elements.progressContainer.addEventListener('click', (e) => this.setProgress(e));
// Volume control
this.elements.volumeBar.addEventListener('click', (e) => this.setVolume(e));
// Audio events
this.audio.addEventListener('timeupdate', () => this.updateProgress());
this.audio.addEventListener('ended', () => this.handleTrackEnd());
this.audio.addEventListener('loadedmetadata', () => this.updateDuration());
// Keyboard shortcuts
document.addEventListener('keydown', (e) => this.handleKeyboard(e));
}
setupVisualizer() {
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
const canvas = this.elements.visualizer;
const ctx = canvas.getContext('2d');
const draw = () => {
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
requestAnimationFrame(draw);
analyser.getByteFrequencyData(dataArray);
ctx.fillStyle = 'rgb(18, 18, 18)';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
const barWidth = (WIDTH / bufferLength) * 2.5;
let barHeight;
let x = 0;
for(let i = 0; i < bufferLength; i++) {
barHeight = dataArray[i] / 2;
ctx.fillStyle = `rgb(33, 150, 243)`;
ctx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
};
draw();
}
loadTrack(index) {
if (index < 0) index = this.playlist.length - 1;
if (index >= this.playlist.length) index = 0;
this.currentTrackIndex = index;
const track = this.playlist[index];
this.audio.src = track.url;
this.elements.albumArt.src = track.artwork;
this.elements.trackTitle.textContent = track.title;
this.elements.trackArtist.textContent = track.artist;
this.updatePlaylistUI();
if (this.isPlaying) {
this.audio.play();
}
}
togglePlay() {
if (this.audio.paused) {
this.audio.play();
this.isPlaying = true;
this.elements.playBtn.innerHTML = '<i class="fas fa-pause"></i>';
} else {
this.audio.pause();
this.isPlaying = false;
this.elements.playBtn.innerHTML = '<i class="fas fa-play"></i>';
}
}
prevTrack() {
this.loadTrack(this.currentTrackIndex - 1);
}
nextTrack() {
this.loadTrack(this.currentTrackIndex + 1);
}
toggleShuffle() {
this.isShuffled = !this.isShuffled;
this.elements.shuffleBtn.classList.toggle('active');
}
toggleRepeat() {
const modes = ['none', 'one', 'all'];
const currentIndex = modes.indexOf(this.repeatMode);
this.repeatMode = modes[(currentIndex + 1) % modes.length];
// Update UI
const icon = this.elements.repeatBtn.querySelector('i');
icon.className = 'fas fa-redo';
if (this.repeatMode === 'one') {
icon.className = 'fas fa-redo-alt';
}
this.elements.repeatBtn.classList.toggle('active', this.repeatMode !== 'none');
}
toggleMute() {
this.audio.muted = !this.audio.muted;
const icon = this.elements.muteBtn.querySelector('i');
icon.className = this.audio.muted ? 'fas fa-volume-mute' : 'fas fa-volume-up';
}
setProgress(e) {
const width = this.elements.progressContainer.clientWidth;
const clickX = e.offsetX;
const duration = this.audio.duration;
this.audio.currentTime = (clickX / width) * duration;
}
setVolume(e) {
const width = this.elements.volumeBar.clientWidth;
const clickX = e.offsetX;
const volume = clickX / width;
this.audio.volume = Math.max(0, Math.min(1, volume));
this.elements.volumeProgress.style.width = `${volume * 100}%`;
}
updateProgress() {
const { currentTime, duration } = this.audio;
const progressPercent = (currentTime / duration) * 100;
this.elements.progress.style.width = `${progressPercent}%`;
this.elements.currentTime.textContent = this.formatTime(currentTime);
}
updateDuration() {
this.elements.duration.textContent = this.formatTime(this.audio.duration);
}
handleTrackEnd() {
if (this.repeatMode === 'one') {
this.audio.play();
} else if (this.repeatMode === 'all') {
this.nextTrack();
} else if (this.currentTrackIndex < this.playlist.length - 1) {
this.nextTrack();
}
}
handleKeyboard(e) {
// Space: Play/Pause
if (e.code === 'Space') {
e.preventDefault();
this.togglePlay();
}
// Left Arrow: Previous Track
else if (e.code === 'ArrowLeft') {
this.prevTrack();
}
// Right Arrow: Next Track
else if (e.code === 'ArrowRight') {
this.nextTrack();
}
// M: Mute/Unmute
else if (e.code === 'KeyM') {
this.toggleMute();
}
}
formatTime(seconds) {
if (isNaN(seconds)) return '0:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, '0')}`;
}
renderPlaylist() {
this.elements.playlistContainer.innerHTML = this.playlist
.map((track, index) => `
<li class="playlist-item ${index === this.currentTrackIndex ? 'active' : ''}"
onclick="player.loadTrack(${index})">
<div>
<div class="playlist-item-title">${track.title}</div>
<div class="playlist-item-artist">${track.artist}</div>
</div>
</li>
`).join('');
}
updatePlaylistUI() {
const items = this.elements.playlistContainer.querySelectorAll('.playlist-item');
items.forEach((item, index) => {
item.classList.toggle('active', index === this.currentTrackIndex);
});
}
}
// Wait for DOM to be fully loaded before initializing the player
document.addEventListener('DOMContentLoaded', () => {
// Initialize player
window.player = new MusicPlayer();
player.initializePlayer();
// Load first track
player.loadTrack(0);
});