-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
486 lines (441 loc) · 14.5 KB
/
app.js
File metadata and controls
486 lines (441 loc) · 14.5 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// ================================================================
// app.js — BeatFlow Internal Music Player
// Assignment 4: OOP + Multimedia Elements
//
// Name: ___________________________
// Date: ___________________________
// ================================================================
//
// INSTRUCTIONS:
// Complete all 4 parts below in order.
// Do NOT modify index.html or styles.css.
// Test in a browser after completing each part.
//
// RECOMMENDED ORDER: Part 1 → Part 2 → Part 3 → Part 4
// ================================================================
// ================================================================
// SAMPLE TRACK DATA — Do not modify
// Each track object has: title, artist, genre, src (audio URL)
// Note: src uses free royalty-free samples from pixabay
// ================================================================
const TRACKS = [
{
title: "Neon Drift",
artist: "The Synthwave Collective",
genre: "Electronic",
src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
},
{
title: "Rooftop Sessions",
artist: "Juno Park",
genre: "Lo-Fi",
src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",
},
{
title: "Midnight Raga",
artist: "Arjun Sharma",
genre: "Fusion",
src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3",
},
{
title: "City Pulse",
artist: "Nadia Voss",
genre: "Pop",
src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3",
},
{
title: "Bass Garden",
artist: "The Synthwave Collective",
genre: "Electronic",
src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3",
},
{
title: "Still Waters",
artist: "Juno Park",
genre: "Lo-Fi",
src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3",
},
];
// ================================================================
// PART 1 — The Track Class (5 points)
//
// TODO: Define a class called Track
//
// Properties (set via constructor):
// - title (string)
// - artist (string)
// - genre (string)
// - src (string — audio URL)
// - _playCount (number, private convention — start at 0)
//
// Getter:
// - get playCount() → returns _playCount
//
// Methods:
// - incrementPlay() → adds 1 to _playCount
// - getInfo() → returns a formatted string:
// '"Title" by Artist [Genre]'
// - toString() → returns the same as getInfo()
// ================================================================
// YOUR CODE HERE
class Track {
constructor(title, artist, genre, src) {
this.title = title;
this.artist = artist;
this.genre = genre;
this.src = src;
this._playCount = 0;
}
get playCount() {
return this._playCount;
}
incrementPlay() {
this._playCount++;
}
getInfo() {
return `"${this.title}" by ${this.artist} [${this.genre}]`;
}
toString() {
return this.getInfo();
}
}
// ================================================================
// PART 2 — The MusicPlayer Class (6 points)
//
// TODO: Define a class called MusicPlayer
//
// Constructor receives: audioElementId (string)
// - this.audio → document.getElementById(audioElementId)
// - this.tracks → empty array []
// - this.currentIndex → -1
// - this.isPlaying → false
//
// Methods:
//
// loadTracks(trackDataArray)
// - Receives the TRACKS array above
// - For each item, create a new Track object and push it
// into this.tracks
// - Call renderTrackList() after loading
// - Call addLog(`Loaded ${this.tracks.length} tracks`)
//
// play(index)
// - Set this.currentIndex = index
// - Get the track: const track = this.tracks[index]
// - Set this.audio.src = track.src
// - Call this.audio.play()
// - Set this.isPlaying = true
// - Call track.incrementPlay()
// - Call updatePlayerUI(track)
// - Call addLog(`▶ Now playing: ${track.getInfo()}`)
//
// pause()
// - Call this.audio.pause()
// - Set this.isPlaying = false
// - Call addLog('⏸ Paused')
// - Update play button text to '▶'
// - Remove 'playing' class from #playBtn and #playerArt
//
// next()
// - Calculate nextIndex: (this.currentIndex + 1) % this.tracks.length
// - Call this.play(nextIndex)
//
// prev()
// - Calculate prevIndex: wrap backwards using tracks.length
// Hint: (this.currentIndex - 1 + this.tracks.length) % this.tracks.length
// - Call this.play(prevIndex)
//
// setVolume(value)
// - Set this.audio.volume = value
// - Update #volPct text to show the percentage (Math.round(value * 100) + '%')
// - Call addLog(`🔊 Volume set to ${Math.round(value * 100)}%`)
//
// getTrackCount()
// - Returns this.tracks.length
// ================================================================
// YOUR CODE HERE
// music player class
class MusicPlayer {
constructor(audioElementId) {
this.audio = document.getElementById(audioElementId);
this.tracks = [];
this.currentIndex = -1;
this.isPlaying = false;
}
loadTracks(trackDataArray) {
trackDataArray.forEach((t) =>
this.tracks.push(new Track(t.title, t.artist, t.genre, t.src)),
);
renderTrackList();
addLog(`Loaded ${this.tracks.length} tracks`);
}
play(index) {
this.currentIndex = index;
const track = this.tracks[index];
this.audio.src = track.src;
this.audio.play();
this.isPlaying = true;
track.incrementPlay();
updatePlayerUI(track);
addLog(`▶ Now playing: ${track.getInfo()}`);
}
pause() {
this.audio.pause();
this.isPlaying = false;
addLog("⏸ Paused");
document.getElementById("playBtn").textContent = "▶";
document.getElementById("playBtn").classList.remove("playing");
document.getElementById("playerArt").classList.remove("playing");
}
next() {
const nextIndex = (this.currentIndex + 1) % this.tracks.length;
this.play(nextIndex);
}
prev() {
const prevIndex =
(this.currentIndex - 1 + this.tracks.length) % this.tracks.length;
this.play(prevIndex);
}
setVolume(value) {
this.audio.volume = value;
document.getElementById("volPct").textContent =
Math.round(value * 100) + "%";
addLog(`🔊 Volume set to ${Math.round(value * 100)}%`);
}
getTrackCount() {
return this.tracks.length;
}
}
// ================================================================
// PART 3 — The Playlist Class (5 points)
// (Extends Track management — uses inheritance)
//
// TODO: Define a class called Playlist
//
// Constructor receives: name (string)
// - this.name → the playlist name
// - this.tracks → empty array []
//
// Methods:
//
// addTrack(trackObject)
// - Push the Track object into this.tracks
// - Call addLog(`Added "${trackObject.title}" to playlist "${this.name}"`)
//
// removeTrack(title)
// - Filter out the track whose title matches (case-insensitive)
// - Update this.tracks with the filtered result
// - Call addLog(`Removed "${title}" from playlist "${this.name}"`)
//
// getTracks()
// - Returns this.tracks array
//
// getSummary()
// - Returns a string:
// '${this.name} — ${this.tracks.length} track(s)'
//
// Then:
// - Create one Playlist instance called "My Favourites"
// - Add the first 3 tracks from the player's track list to it
// after the player is initialised (see Part 4 wiring below)
// - Call renderPlaylists() to show it in the sidebar
// ================================================================
// YOUR CODE HERE
// playlist class
class Playlist extends Track {
constructor(name) {
super(name, "", "", "");
this.name = name;
this.tracks = [];
}
addTrack(trackObject) {
this.tracks.push(trackObject);
addLog(`Added "${trackObject.title}" to playlist "${this.name}"`);
}
removeTrack(title) {
this.tracks = this.tracks.filter(
(t) => t.title.toLowerCase() !== title.toLowerCase(),
);
addLog(`Removed "${title}" from playlist "${this.name}"`);
}
getTracks() {
return this.tracks;
}
getSummary() {
return `${this.name} — ${this.tracks.length} track(s)`;
}
}
// ================================================================
// PART 4 — Wiring the UI (4 points)
//
// TODO: Connect the classes above to the DOM
//
// 1. Create a MusicPlayer instance:
// const player = new MusicPlayer('audioPlayer')
//
// 2. Call player.loadTracks(TRACKS)
//
// 3. Wire up #playBtn click:
// - If player.isPlaying → call player.pause()
// - Else if currentIndex === -1 → call player.play(0)
// - Else → call player.play(player.currentIndex)
//
// 4. Wire up #nextBtn → call player.next()
//
// 5. Wire up #prevBtn → call player.prev()
//
// 6. Wire up #volumeSlider input event:
// - Call player.setVolume(parseFloat(slider.value))
//
// 7. Wire up #clearLogBtn → clear the log (see addLog helper below)
//
// 8. Wire up #createPlaylistBtn:
// - Use prompt() to ask for a playlist name
// - If a name is given, create a new Playlist and call renderPlaylists()
//
// 9. Wire up each track item in the sidebar:
// (Already handled inside renderTrackList — but make sure your
// play() method marks the active track correctly)
//
// After wiring:
// - Create the "My Favourites" playlist (see Part 3)
// - Add player.tracks[0], [1], [2] to it
// - Call renderPlaylists()
// ================================================================
// Initialize playlists array BEFORE creating player
const playlists = [];
// YOUR CODE HERE
const player = new MusicPlayer("audioPlayer");
player.loadTracks(TRACKS);
// Create the "My Favourites" playlist and add tracks to it
const myFavourites = new Playlist("My Favourites");
myFavourites.addTrack(player.tracks[0]);
myFavourites.addTrack(player.tracks[1]);
myFavourites.addTrack(player.tracks[2]);
playlists.push(myFavourites);
renderPlaylists();
// wire up playBtn
document.getElementById("playBtn").addEventListener("click", () => {
if (player.isPlaying) {
player.pause();
} else if (player.currentIndex === -1) {
player.play(0);
} else {
player.play(player.currentIndex);
}
});
// wire up next and prev buttons
document.getElementById("nextBtn").addEventListener("click", () => {
player.next();
});
document.getElementById("prevBtn").addEventListener("click", () => {
player.prev();
});
// wire up volume slider
document.getElementById("volumeSlider").addEventListener("input", (e) => {
player.setVolume(parseFloat(e.target.value));
});
// wire up clear log button
document.getElementById("clearLogBtn").addEventListener("click", () => {
const container = document.getElementById("logEntries");
container.innerHTML =
'<div class="log-placeholder">Activity log cleared.</div>';
});
// wire up create playlist button
document.getElementById("createPlaylistBtn").addEventListener("click", () => {
const name = prompt("Enter playlist name:");
if (name) {
const newPlaylist = new Playlist(name);
playlists.push(newPlaylist);
renderPlaylists();
}
});
// ================================================================
// HELPER FUNCTIONS — Provided for you. Do not modify.
// These handle all the DOM rendering so you can focus on OOP.
// ================================================================
/**
* Renders the track list in the sidebar.
* Call this inside loadTracks() after populating this.tracks.
*/
function renderTrackList() {
const list = document.getElementById("trackList");
const countEl = document.getElementById("trackCount");
list.innerHTML = "";
countEl.textContent = player.getTrackCount();
player.tracks.forEach((track, index) => {
const item = document.createElement("div");
item.classList.add("track-item");
item.setAttribute("data-index", index);
item.innerHTML = `
<span class="track-num">${index + 1}</span>
<div class="track-details">
<div class="track-name">${track.title}</div>
<div class="track-artist">${track.artist}</div>
</div>
<span class="track-genre">${track.genre}</span>
`;
item.addEventListener("click", () => player.play(index));
list.appendChild(item);
});
}
/**
* Updates the main player UI when a track is loaded.
* Call this inside play() with the current Track object.
*/
function updatePlayerUI(track) {
document.getElementById("playerTrackName").textContent = track.title;
document.getElementById("playerArtist").textContent = track.artist;
document.getElementById("playerGenre").textContent = track.genre;
document.getElementById("nowPlayingName").textContent = track.title;
document.getElementById("nowPlayingGenre").textContent = track.genre;
document.getElementById("playBtn").textContent = "⏸";
document.getElementById("playBtn").classList.add("playing");
document.getElementById("playerArt").classList.add("playing");
// Highlight active track in sidebar
document.querySelectorAll(".track-item").forEach((el, i) => {
el.classList.toggle("active", i === player.currentIndex);
});
}
/**
* Renders the playlist list in the sidebar.
* Call this whenever playlists are created or updated.
*/
function renderPlaylists() {
const container = document.getElementById("playlistList");
if (playlists.length === 0) {
container.innerHTML = '<div class="empty-msg">No playlists yet.</div>';
return;
}
container.innerHTML = "";
playlists.forEach((pl) => {
const div = document.createElement("div");
div.classList.add("playlist-item");
div.innerHTML = `
<div>${pl.name}</div>
<div class="playlist-count">${pl.getTracks().length} track(s)</div>
`;
container.appendChild(div);
});
}
/**
* Adds a timestamped entry to the activity log.
* Call addLog('your message') anywhere in your code.
*/
function addLog(message, type = "") {
const container = document.getElementById("logEntries");
const ph = container.querySelector(".log-placeholder");
if (ph) container.removeChild(ph);
const entry = document.createElement("div");
entry.classList.add("log-entry");
if (type) entry.classList.add(`log-${type}`);
const now = new Date();
const time = [now.getHours(), now.getMinutes(), now.getSeconds()]
.map((n) => String(n).padStart(2, "0"))
.join(":");
entry.innerHTML = `<span class="log-time">[${time}]</span> ${message}`;
container.appendChild(entry);
const all = container.querySelectorAll(".log-entry");
if (all.length > 12) container.removeChild(all[0]);
container.scrollTop = container.scrollHeight;
}