-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathedirom-audio-player.js
643 lines (506 loc) · 20 KB
/
edirom-audio-player.js
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
/**
* Represents the EdiromAudioPlayer custom element.
* @class
* @extends HTMLElement
*/
class EdiromAudioPlayer extends HTMLElement {
/**
* Creates an instance of EdiromAudioPlayer.
* @constructor
*/
constructor() {
super();
/** attach shadow root with mode "open" */
this.attachShadow({ mode: 'open' });
/** set global properties */
this.track = this.getAttribute('track') || 0;
this.tracks = this.getAttribute('tracks') || '[]';
this.height = this.getAttribute('height') || '100%';
this.width = this.getAttribute('width') || '100%';
this.state = this.getAttribute('state') || 'pause';
this.start = this.getAttribute('start') || 0;
this.end = this.getAttribute('end');
this.playbackrate = this.getAttribute('playbackrate') || 1;
this.playbackmode = this.getAttribute('playbackmode') || 'all';
this.displaymode = this.getAttribute('displaymode') || 'controls-lg';
//Define a FontFace
const font = new FontFace("Material Symbols Outlined", "url(https://fonts.gstatic.com/s/materialsymbolsoutlined/v192/kJF1BvYX7BgnkSrUwT8OhrdQw4oELdPIeeII9v6oDMzByHX9rA6RzaxHMPdY43zj-jCxv3fzvRNU22ZXGJpEpjC_1v-p_4MrImHCIJIZrDCvHOej.woff2)", {
style: "normal",
weight: "100 700"
});
// wait for font
font.load().then((loaded_face) => {
document.fonts.add(loaded_face)
// append content
this.shadowRoot.innerHTML += `
<style>
.mso {
font-family: 'Material Symbols Outlined';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-moz-font-feature-settings: 'liga';
-moz-osx-font-smoothing: grayscale;
}
</style>
${this.getCSS()}
`;
// add content div
const contentDiv = document.createElement('div');
contentDiv.id = 'content';
this.shadowRoot.appendChild(contentDiv);
// attach player html
contentDiv.innerHTML = this.getPlayerHTML();
// add event listeners
this.addEventListeners();
}).catch((error) => { });
}
/**
* Returns the list of observed attributes for the EdiromAudioPlayer custom element.
* @static
* @returns {Array<string>} The list of observed attributes.
*/
static get observedAttributes() {
return ['track', 'tracks', 'height', 'width', 'state', 'start', 'end', 'playbackrate', 'playbackmode', 'displaymode'];
}
/**
* Invoked when the custom element is connected from the document's DOM.
*/
connectedCallback() {
// get necessary objects
const contentDiv = this.shadowRoot.querySelector('#content');
const audioPlayer = this.shadowRoot.querySelector('#audioPlayer');
// overwrite content if content div is ready
if (!contentDiv === null) {
contentDiv.innerHTML = this.getPlayerHTML();
}
// set event listeners again
this.addEventListeners();
}
/**
* Invoked when the custom element is disconnected from the document's DOM.
*/
disconnectedCallback() { }
/**
* Invoked when the custom element is moved to a new document.
*/
adoptedCallback() { }
/**
* Invoked when one of the custom element's attributes is added, removed, or changed.
* @param {string} property - The name of the attribute that was changed.
* @param {*} oldValue - The previous value of the attribute.
* @param {*} newValue - The new value of the attribute.
*/
attributeChangedCallback(property, oldValue, newValue) {
// handle property change
this.set(property, newValue);
}
/**
* Sets the value of a global property and triggers property update events.
* @param {string} property - The name of the property to set.
* @param {*} newPropertyValue - The new value to set for the property.
*/
set(property, newPropertyValue) {
// set internal and html properties
this[property] = newPropertyValue;
// custom event for property update
const event = new CustomEvent('communicate-' + property + '-update', {
detail: { [property]: newPropertyValue },
bubbles: true
});
this.dispatchEvent(event);
// further handling of property change
this.handlePropertyChange(property, newPropertyValue);
}
/**
* Returns the HTML content for the player.
* @returns {string} The HTML content for the player.
*/
getPlayerHTML() {
let playerInnerHTML;
playerInnerHTML = this.getControlsHTML(['skip_previous', 'play_arrow', 'skip_next', 'playlist_remove']);
playerInnerHTML += this.getTimeHTML();
playerInnerHTML += this.getTracksHTML();
return '<div id="player" class="' + this.displaymode + '">' + playerInnerHTML + '</div>';
}
/**
* Returns the HTML content for the control buttons.
* @param {Array<string>} buttons - The list of button names.
* @returns {string} The HTML content for the control buttons.
*/
getControlsHTML(buttons) {
const tracks = JSON.parse(this.tracks);
const currentTrack = tracks[this.track];
const trackSteps = [{ "replay": "0" }, { "skip_previous": "-1" }, { "skip_next": "+1" }];
let controlsDiv = document.createElement('div');
controlsDiv.id = 'controls';
// Create and fill audio element
let audioElem = document.createElement('audio');
audioElem.id = 'audioPlayer';
audioElem.controls = true;
audioElem.style.display = 'none';
// Create and fill source element
let sourceElem = document.createElement('source');
sourceElem.src = currentTrack.src;
sourceElem.type = currentTrack.type;
sourceElem.innerHTML = 'Your browser does not support the audio element.';
// Append elements
audioElem.appendChild(sourceElem);
controlsDiv.appendChild(audioElem);
// Create and fill button elements
buttons.forEach(button => {
let buttonElem = document.createElement('button');
buttonElem.id = button + 'Button';
buttonElem.title = button;
// add class and data-trackstep attribute to buttons to indicate how many tracks should be forwarded or rewinded
if (trackSteps.find(step => step[button])) {
buttonElem.classList.add('track-toggler');
buttonElem.dataset.trackstep = trackSteps.find(step => step[button])[button];
}
// Add icon to button
buttonElem.innerHTML = '<span class="mso">' + button + '</span>';
// Append button to controlsDiv
controlsDiv.appendChild(buttonElem);
});
return controlsDiv.outerHTML;
}
/**
* Returns the HTML content for the time information.
* @returns {string} The HTML content for the time information.
*/
getTimeHTML() {
var timeHTML;
timeHTML = `
<div id="timeInfo">
<input type="range" id="progressSlider" min="0" max="100" value="0">
<span id="currentTime">0:00</span> / <span id="totalTime">0:00</span>
</div>
`;
return timeHTML;
}
/**
* Returns the HTML content for the tracks.
* @returns {string} The HTML content for the tracks.
*/
getTracksHTML() {
const tracks = JSON.parse(this.tracks);
const tracksHTML = tracks.map((track, idx) => `<div class="track-button track-toggler${idx == this.track ? ' current' : ''}" data-trackidx="${idx}">
<div class="track-title">${track.title}</div>
<div class="track-subtitle">${track.composer} - ${track.work}</div>
</div>
`).join('');
return '<div id="tracks">' + tracksHTML + '</div>';
}
/**
* Returns the CSS styles for the player.
* @returns {string} The CSS styles for the player.
*/
getCSS() {
return `
<style>
#player {
height: 100%;
width: 100%;
container: player / inline-size;
}
#player.hidden{
display: none;
}
#controls {
display: flex;
align-items: center;
gap: 10px;
}
#controls button {
display: inline-block;
border: none;
background: none;
}
#controls #replayButton,
#controls #fast_forwardButton,
#controls #fast_rewindButton {
display: none;
}
#timeInfo {
margin-top: 10px;
}
#timeInfo input {
min-width: 70%;
}
#timeInfo span {
font-size: 0.875rem;
font-family: 'Roboto', sans-serif;
text-align: center;
}
.track-button {
display: block;
margin: 10px 0;
padding: 6px 16px;
font-size: 0.875rem;
font-weight: 500;
line-height: 1.75;
letter-spacing: 0.02857em;
color: rgba(0, 0, 0, 0.87);
border: none;
border-radius: 4px;
background-color: #e6e6e6;
transition: background-color 0.3s;
position: relative;
}
.track-button:hover, .track-button.current {
background-color: #d5d5d5;
}
.track-button:active {
background-color: #aaaaaa;
}
.track-button:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.12);
}
/* height-dependent rules */
/* width-dependent rules */
@container player (width > 380px){
#controls #replayButton,
#controls #fast_forwardButton,
#controls #fast_rewindButton {
display: inline-block;
}
}
</style>
`;
}
/**
* Handles property changes for the audio player.
* @param {string} property - The name of the property being changed.
* @param {any} newPropertyValue - The new value of the property.
*/
handlePropertyChange(property, newPropertyValue) {
// get necessary objects and check if available
const audioPlayer = this.shadowRoot.querySelector('#audioPlayer');
const playerDiv = this.shadowRoot.querySelector('#player');
const playButton = this.shadowRoot.querySelector('#play_arrowButton');
const source = this.shadowRoot.querySelector('source');
//if(audioPlayer === null || playerDiv === null || playButton === null || source === null )
// return;
// handle property change
switch(property) {
// handle track setting
case 'track':
// set info at source element
const tracks =JSON.parse(this.tracks);
const nextTrack = tracks[newPropertyValue];
if(source != null){
source.src = nextTrack.src;
source.type = nextTrack.type;
}
// mark active track, if exists in DOM, therefore querySelectorAll() is used
this.shadowRoot.querySelectorAll(".track-button").forEach((e) => { e.classList.remove('current'); });
this.shadowRoot.querySelectorAll('.track-button[data-trackidx="'+this.track+'"]').forEach((e) => { e.classList.add('current') });
// handle audio player state
(audioPlayer != null) ? audioPlayer.load() : console.log("Audio player not available");
this.set('start', this.start);
this.set('state', 'play');
break;
// handle state setting
case 'state':
// handle audio player state
if (audioPlayer != null && playButton != null) {
if (newPropertyValue === 'play' && audioPlayer != null && playButton != null) {
audioPlayer.play();
playButton.innerHTML = '<span class="mso">pause</span>';
playButton.setAttribute('title', 'pause');
} else if(newPropertyValue === 'pause' && audioPlayer != null && playButton != null) {
(audioPlayer != null) ? audioPlayer.pause() : console.log("Audio player not available");
playButton.innerHTML = '<span class="mso">play_arrow</span>';
playButton.setAttribute('title', 'play');
} else {
console.log("Invalid audio player state property: '"+newPropertyValue+"'");
}
}
break;
// handle time setting
case 'start':
(audioPlayer != null) ? audioPlayer.currentTime = parseFloat(newPropertyValue) : console.log("Audio player not available");
break;
// handle end setting
case 'end':
break;
// handle playbackrate setting
case 'playbackrate':
(audioPlayer != null) ? audioPlayer.playbackRate = newPropertyValue : console.log("Audio player not available");
break;
// handle playbackmode setting
case 'playbackmode':
break;
// handle displaymode setting
case 'displaymode':
const tracksDiv = this.shadowRoot.querySelector('#tracks');
const sliderDiv = this.shadowRoot.querySelector('#timeInfo');
const tracksButton = this.shadowRoot.querySelector('#playlist_removeButton');
switch(this.displaymode) {
case 'hidden':
break;
case 'controls-sm':
if(tracksDiv === null) return;
tracksDiv.style.display = 'none';
sliderDiv.style.display = 'none';
tracksButton.innerHTML = '<span class="mso">playlist_add</span>';
break;
case 'controls-md':
if(tracksDiv === null) return;
tracksDiv.style.display = 'none';
sliderDiv.style.display = 'block';
tracksButton.innerHTML = '<span class="mso">playlist_add</span>';
break;
case 'controls-lg':
if(tracksDiv === null) return;
tracksDiv.style.display = 'block';
sliderDiv.style.display = 'block';
tracksButton.innerHTML = '<span class="mso">playlist_remove</span>';
break;
case 'tracks-sm':
break;
case 'tracks-md':
break;
case 'tracks-lg':
break;
default:
console.log("Invalid displaymode: '"+this.displaymode+"'");
}
break;
// handle height setting
case 'height':
playerDiv.style.height = newPropertyValue;
break;
// handle width setting
case 'width':
playerDiv.style.width = newPropertyValue;
break;
// handle tracks setting
case 'tracks':
// if content div is ready, update it
if(!this.shadowRoot.querySelector('#content') === null){
this.shadowRoot.querySelector('#content').innerHTML = this.getPlayerHTML();
}
break;
// handle default
default:
console.log("Invalid property: '"+property+"'");
}
}
/**
* Adds event listeners to various elements in the audio player component.
* These event listeners handle play/pause button clicks, track toggler clicks,
* audio player events (duration change, time update), progress slider input,
* and playlist remove button clicks.
*/
addEventListeners() {
const audioPlayer = this.shadowRoot.querySelector('#audioPlayer');
const progressSlider = this.shadowRoot.querySelector('#progressSlider');
const currentTimeDisplay = this.shadowRoot.querySelector('#currentTime');
const totalTimeDisplay = this.shadowRoot.querySelector('#totalTime');
/** Event listener for play/pause button */
this.shadowRoot.querySelectorAll('#play_arrowButton').forEach(el => {
el.addEventListener('click', () => {
return audioPlayer.paused ? this.set('state', 'play') : this.set('state', 'pause');
});
});
/**
* Event listener for prev/next buttons.
* It listens to all elements with class .track-toggler and reads the data-trackstep attribute to get an info how many tracks
* should be forwarded or rewinded. This allows for buttons to forward or rewind any number of tracks -> +/-n steps
*/
this.shadowRoot.querySelectorAll('.track-toggler').forEach(el => {
el.addEventListener('click', (evt) => {
const tracksJSON = JSON.parse(this.tracks);
const trackStep = evt.currentTarget.dataset.trackstep;
const trackIdx = evt.currentTarget.dataset.trackidx;
var nextTrackIndex = !!trackIdx ? trackIdx : (parseInt(this.track) + parseInt(trackStep));
if(nextTrackIndex < 0) { nextTrackIndex = tracksJSON.length - 1 }
if(nextTrackIndex >= tracksJSON.length) { nextTrackIndex = 0 }
this.set('track', nextTrackIndex);
});
});
/** Event listeners for audio player */
this.shadowRoot.querySelectorAll('#audioPlayer').forEach(el => {
// Event listener for duration change to update total time display
el.addEventListener('durationchange', (evt) => {
const totalMinutes = Math.floor(audioPlayer.duration / 60);
const totalSeconds = Math.floor(audioPlayer.duration % 60);
if(totalTimeDisplay) totalTimeDisplay.textContent = `${totalMinutes}:${totalSeconds < 10 ? '0' : ''}${totalSeconds}`;
});
el.addEventListener('timeupdate', (evt) => {
// Send update event to host
const event = new CustomEvent('communicate-time-update', {
detail: { time: audioPlayer.currentTime },
bubbles: true
});
this.dispatchEvent(event);
// update current time display
if(currentTimeDisplay){
const currentMinutes = Math.floor(audioPlayer.currentTime / 60);
const currentSeconds = Math.floor(audioPlayer.currentTime % 60);
currentTimeDisplay.textContent = `${currentMinutes}:${currentSeconds < 10 ? '0' : ''}${currentSeconds}`;
}
// update progress slider
if(progressSlider){
const progress = (audioPlayer.currentTime / audioPlayer.duration) * 100;
progressSlider.value = progress;
}
// if audioPlayer is currently playing and end is reached, pause there
const end = Number(this.end);
if(this.state === 'play' && !isNaN(Number(end)) && end > 0 ) {
if (audioPlayer.currentTime >= end || audioPlayer.currentTime >= audioPlayer.duration) {
this.set('state', 'pause');
// and now decide how to proceed
switch(this.playbackmode) {
case 'off':
// do nothing
break;
case 'repeat':
// go to next track and play from start to end
let nextButton = this.shadowRoot.querySelector('#skip_nextButton');
nextButton.click();
break;
case 'repeatOne':
audioPlayer.currentTime = this.start;
audioPlayer.play();
break;
case 'shuffle':
// shuffle tracks
let randomTrackIndex = Math.floor(Math.random() * JSON.parse(this.tracks).length);
this.set('track', randomTrackIndex);
break;
default:
console.log("Invalid playbackmode: '"+this.playbackmode+"'");
}
}
}
// handle playbackmodes (shuffle, repeat, repeatOne)
});
});
/** Event listeners for tracking progress slider */
this.shadowRoot.querySelectorAll('#progressSlider').forEach(el => {
el.addEventListener('input', (evt) => {
audioPlayer.currentTime = (evt.target.value / 100) * audioPlayer.duration;
});
});
this.shadowRoot.querySelectorAll('#playlist_removeButton').forEach(el => {
el.addEventListener('click', (evt) => {
const tracksDiv = this.shadowRoot.querySelector('#tracks');
const tracksButton = this.shadowRoot.querySelector('#playlist_removeButton');
tracksButton.innerHTML = tracksDiv.style.display === 'none' ? '<span class="mso">playlist_remove</span>' : '<span class="mso">playlist_add</span>';
tracksDiv.style.display = tracksDiv.style.display === 'none' ? 'block' : 'none';
});
});
}
}
/** Define the custom element */
customElements.define('edirom-audio-player', EdiromAudioPlayer);