-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedia-player-lego.js
More file actions
1105 lines (944 loc) · 33.6 KB
/
media-player-lego.js
File metadata and controls
1105 lines (944 loc) · 33.6 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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MEDIA PLAYER CONTAINER
* Bottom-left container with simple media player for local files
*/
let isMediaPlayerInitialized = false;
let currentMediaFile = null;
let mediaIsPlaying = false;
let mediaCurrentTime = 0;
let mediaDuration = 0;
// Web Audio API for visualization
let mediaAudioContext = null;
let mediaAnalyser = null;
let mediaSource = null;
let mediaDataArray = null;
let mediaAnimationId = null;
// Spectrogram state
let spectrogramCanvas = null;
let spectrogramCtx = null;
let spectrogramAnimationId = null;
let spectrogramX = 0;
let spectrogramBins = 64;
let spectrogramZoomLevels = [1, 2, 5];
let spectrogramZoomIndex = 0;
// Hex grid state
let hexCanvas = null;
let hexCtx = null;
let hexAnimationId = null;
/**
* Setup Web Audio API for visualization
*/
function setupAudioContext() {
if (!mediaAudioContext) {
mediaAudioContext = new (window.AudioContext || window.webkitAudioContext)();
mediaAnalyser = mediaAudioContext.createAnalyser();
mediaAnalyser.fftSize = 256;
mediaAnalyser.smoothingTimeConstant = 0.8;
const bufferLength = mediaAnalyser.frequencyBinCount;
mediaDataArray = new Uint8Array(bufferLength);
console.log('MEDIA PLAYER: Web Audio API initialized');
}
}
/**
* Connect audio element to Web Audio API
*/
function connectAudioToVisualizer(audioElement) {
if (!mediaAudioContext || !mediaAnalyser) {
setupAudioContext();
}
// Disconnect previous source if exists
if (mediaSource) {
mediaSource.disconnect();
}
// Create new source from audio element
mediaSource = mediaAudioContext.createMediaElementSource(audioElement);
mediaSource.connect(mediaAnalyser);
mediaAnalyser.connect(mediaAudioContext.destination);
console.log('MEDIA PLAYER: Audio connected to visualizer');
// Start visualization loop
startVisualization();
// Ensure global orb exists (animates with audio)
if (typeof initOrb === 'function') {
initOrb();
}
}
/**
* Start audio visualization loop
*/
function startVisualization() {
if (mediaAnimationId) {
cancelAnimationFrame(mediaAnimationId);
}
function visualize() {
if (!mediaAnalyser || !mediaDataArray) return;
mediaAnalyser.getByteFrequencyData(mediaDataArray);
// Calculate audio intensity (0-1)
let sum = 0;
for (let i = 0; i < mediaDataArray.length; i++) {
sum += mediaDataArray[i];
}
const intensity = sum / (mediaDataArray.length * 255);
// Calculate scale based on bass frequencies (first 20% of data)
const bassEnd = Math.floor(mediaDataArray.length * 0.2);
let bassSum = 0;
for (let i = 0; i < bassEnd; i++) {
bassSum += mediaDataArray[i];
}
const bassIntensity = bassSum / (bassEnd * 255);
const scale = 1 + (bassIntensity * 2); // Scale from 1 to 3
// Update orb if it exists
if (typeof updateOrbIntensity === 'function') {
updateOrbIntensity(intensity);
}
if (typeof updateOrbScale === 'function') {
updateOrbScale(scale);
}
mediaAnimationId = requestAnimationFrame(visualize);
}
visualize();
}
/**
* Stop audio visualization
*/
function stopVisualization() {
if (mediaAnimationId) {
cancelAnimationFrame(mediaAnimationId);
mediaAnimationId = null;
}
// Reset orb
if (typeof updateOrbIntensity === 'function') {
updateOrbIntensity(0);
}
if (typeof updateOrbScale === 'function') {
updateOrbScale(1);
}
// Stop spectrogram
stopSpectrogram();
// Stop hex grid
stopHexGrid();
}
/**
* Initialize orb in media player container
*/
function initOrbInMediaPlayer() {
const container = document.getElementById('orb-visualizer-container');
if (!container) return;
// Clear existing orb
container.innerHTML = '';
// Create orb canvas
const canvas = document.createElement('canvas');
canvas.className = 'orb-canvas';
canvas.width = 400;
canvas.height = 200;
container.appendChild(canvas);
const ctx = canvas.getContext('2d');
let time = 0;
let animationId = null;
// Simple Perlin noise function (from orb.js)
function noise(x, y) {
const n = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453;
return (n - Math.floor(n));
}
function smoothstep(edge0, edge1, x) {
const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));
return t * t * (3 - 2 * t);
}
function perlin(x, y) {
const xi = Math.floor(x);
const yi = Math.floor(y);
const xf = x - xi;
const yf = y - yi;
const u = smoothstep(0, 1, xf);
const v = smoothstep(0, 1, yf);
const n00 = noise(xi, yi);
const n01 = noise(xi, yi + 1);
const n10 = noise(xi + 1, yi);
const n11 = noise(xi + 1, yi + 1);
const x1 = n00 + u * (n10 - n00);
const x2 = n01 + u * (n11 - n01);
return x1 + v * (x2 - x1);
}
let audioIntensity = 0;
let scale = 1;
function animate() {
time += 0.005;
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Apply scale transformation
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.scale(scale, scale);
ctx.translate(-canvas.width / 2, -canvas.height / 2);
// Create image data
const imageData = ctx.createImageData(canvas.width, canvas.height);
const data = imageData.data;
// Perlin noise parameters
const spatialScale = 4;
const timeScale = 1;
const noiseAmplitude = 0.7 + (audioIntensity * 2);
const noiseOffset = 0;
const gridDensity = 1;
// Generate noise
for (let x = 0; x < canvas.width; x += gridDensity) {
for (let y = 0; y < canvas.height; y += gridDensity) {
const nx = x / canvas.width * spatialScale;
const ny = y / canvas.height * spatialScale;
const nt = time * timeScale;
let n = perlin(nx, ny + nt) * noiseAmplitude + noiseOffset;
const value = Math.max(0, Math.min(1, n));
const index = (y * canvas.width + x) * 4;
const alpha = value * 255 * (1 + audioIntensity);
// Blue glow effect
data[index] = 0; // R
data[index + 1] = 100; // G
data[index + 2] = 255; // B
data[index + 3] = alpha; // A
}
}
ctx.putImageData(imageData, 0, 0);
ctx.restore();
animationId = requestAnimationFrame(animate);
}
// Start animation
animate();
// Add visible class after delay
setTimeout(() => {
canvas.classList.add('visible');
}, 10);
// Store animation ID for cleanup
canvas._animationId = animationId;
// Keep local canvas reactive without overriding global orb updaters
// The global orb (orb.js) will be updated from startVisualization()
// via updateOrbIntensity / updateOrbScale.
console.log('MEDIA PLAYER: Orb visualizer initialized');
}
/**
* Spectrogram: init and loop
*/
function initSpectrogram() {
const holder = document.getElementById('spectrogram');
if (!holder) return;
holder.innerHTML = '';
spectrogramCanvas = document.createElement('canvas');
spectrogramCanvas.className = 'spectrogram-canvas';
// Fit holder size
spectrogramCanvas.width = holder.clientWidth || 380;
spectrogramCanvas.height = holder.clientHeight || 90;
holder.appendChild(spectrogramCanvas);
spectrogramCtx = spectrogramCanvas.getContext('2d');
spectrogramX = 0;
// Setup click to cycle zoom levels (100%, 200%, 500%)
holder.style.cursor = 'ew-resize';
holder.addEventListener('click', function() {
spectrogramZoomIndex = (spectrogramZoomIndex + 1) % spectrogramZoomLevels.length;
applySpectrogramZoom();
});
applySpectrogramZoom();
}
function applySpectrogramZoom() {
const holder = document.getElementById('spectrogram');
if (!holder || !spectrogramCanvas) return;
const scale = spectrogramZoomLevels[spectrogramZoomIndex];
// Stretch canvas horizontally via CSS width; bitmap remains same
spectrogramCanvas.style.width = `${scale * 100}%`;
}
// Viridis colormap (sampled stops with linear interpolation)
function viridisColor(t) {
if (isNaN(t)) t = 0;
t = Math.max(0, Math.min(1, t));
const stops = [
{ t: 0.0, r: 68, g: 1, b: 84 }, //rgba(0, 0, 0, 0.1)
{ t: 0.25, r: 59, g: 82, b: 139 }, // #3b528b
{ t: 0.50, r: 33, g: 145, b: 140 }, // #21918c
{ t: 0.75, r: 94, g: 201, b: 97 }, // #5ec961
{ t: 0.90, r: 170, g: 220, b: 50 }, // ~
{ t: 1.0, r: 253, g: 231, b: 37 } // #fde725
];
let a = stops[0], b = stops[stops.length - 1];
for (let i = 0; i < stops.length - 1; i++) {
if (t >= stops[i].t && t <= stops[i + 1].t) { a = stops[i]; b = stops[i + 1]; break; }
}
const span = (b.t - a.t) || 1;
const k = (t - a.t) / span;
const R = Math.round(a.r + (b.r - a.r) * k);
const G = Math.round(a.g + (b.g - a.g) * k);
const B = Math.round(a.b + (b.b - a.b) * k);
return { r: R, g: G, b: B };
}
function startSpectrogram() {
if (!spectrogramCtx || !mediaAnalyser) return;
if (spectrogramAnimationId) cancelAnimationFrame(spectrogramAnimationId);
const tmpData = new Uint8Array(mediaAnalyser.frequencyBinCount);
const draw = () => {
// Resize canvas if holder size changed
const holder = document.getElementById('spectrogram');
if (holder && (spectrogramCanvas.width !== holder.clientWidth || spectrogramCanvas.height !== holder.clientHeight)) {
const old = spectrogramCtx.getImageData(0, 0, spectrogramCanvas.width, spectrogramCanvas.height);
spectrogramCanvas.width = holder.clientWidth;
spectrogramCanvas.height = holder.clientHeight;
spectrogramCtx.putImageData(old, 0, 0);
}
mediaAnalyser.getByteFrequencyData(tmpData);
// Shift existing image 1px left to create waterfall right->left
spectrogramCtx.drawImage(
spectrogramCanvas,
1, 0, spectrogramCanvas.width - 1, spectrogramCanvas.height,
0, 0, spectrogramCanvas.width - 1, spectrogramCanvas.height
);
// Compute bins to draw as vertical column at right edge
const bins = spectrogramBins;
const binSize = Math.max(1, Math.floor(tmpData.length / bins));
const colX = spectrogramCanvas.width - 1;
const h = spectrogramCanvas.height;
const rowHeight = h / bins;
for (let i = 0; i < bins; i++) {
const start = i * binSize;
const end = Math.min(start + binSize, tmpData.length);
let sum = 0;
for (let j = start; j < end; j++) sum += tmpData[j];
const v = sum / (end - start); // 0..255
const t = v / 255; // normalize
// Skip very low energy to keep background transparent
const threshold = 0.12;
if (t <= threshold) continue;
const nt = (t - threshold) / (1 - threshold); // 0..1 after threshold
const c = viridisColor(t);
const alpha = 0.18 + nt * 0.72; // light transparency on quiet, stronger on loud
spectrogramCtx.fillStyle = `rgba(${c.r}, ${c.g}, ${c.b}, ${alpha.toFixed(3)})`;
const y = Math.floor(h - (i + 1) * rowHeight);
spectrogramCtx.fillRect(colX, y, 1, Math.ceil(rowHeight));
}
spectrogramAnimationId = requestAnimationFrame(draw);
};
draw();
}
function stopSpectrogram() {
if (spectrogramAnimationId) {
cancelAnimationFrame(spectrogramAnimationId);
spectrogramAnimationId = null;
}
}
// Hex grid rendering (audio-reactive)
function initHexGrid() {
const holder = document.getElementById('hexgrid');
if (!holder) return;
holder.innerHTML = '';
hexCanvas = document.createElement('canvas');
hexCanvas.className = 'hexgrid-canvas';
hexCanvas.width = holder.clientWidth || 380*3;
hexCanvas.height = holder.clientHeight || 110*3;
holder.appendChild(hexCanvas);
hexCtx = hexCanvas.getContext('2d');
}
function startHexGrid() {
if (!hexCtx || !mediaAnalyser) return;
if (hexAnimationId) cancelAnimationFrame(hexAnimationId);
const tmp = new Uint8Array(mediaAnalyser.frequencyBinCount);
const draw = () => {
// Resize if holder changed
const holder = document.getElementById('hexgrid');
if (holder && (hexCanvas.width !== holder.clientWidth || hexCanvas.height !== holder.clientHeight)) {
hexCanvas.width = holder.clientWidth;
hexCanvas.height = holder.clientHeight;
}
mediaAnalyser.getByteFrequencyData(tmp);
// Overall audio level (0..1)
let sum = 0; for (let i = 0; i < tmp.length; i++) sum += tmp[i];
const audioLevel = sum / (tmp.length * 255);
hexCtx.clearRect(0, 0, hexCanvas.width, hexCanvas.height);
const hexSize = 4;
const hexWidth = hexSize * 6;
const hexHeight = hexSize * Math.sqrt(3);
const cols = Math.ceil(hexCanvas.width / (hexSize * 1.5)) + 1;
const rows = Math.ceil(hexCanvas.height / hexHeight) + 1;
const centerX = hexCanvas.width / 2;
const centerY = hexCanvas.height / 2;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const x = col * hexSize * 1.5 + (row % 2) * hexSize * 0.75;
const y = row * hexHeight;
const dx = x - centerX; const dy = y - centerY;
const distance = Math.sqrt(dx * dx + dy * dy);
const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY);
const normalizedDistance = distance / maxDistance;
const intensity = audioLevel * (1 - normalizedDistance * 0.5) * 0.6;
if (intensity > 0.15) {
hexCtx.beginPath();
for (let i = 0; i < 6; i++) {
const angle = (Math.PI / 3) * i;
const hx = x + hexSize * Math.cos(angle);
const hy = y + hexSize * Math.sin(angle);
if (i === 0) hexCtx.moveTo(hx, hy); else hexCtx.lineTo(hx, hy);
}
hexCtx.closePath();
const lightness = 70 - (normalizedDistance * 40) + (intensity * 20);
hexCtx.fillStyle = `hsl(210, 60%, ${lightness}%)`;
hexCtx.fill();
hexCtx.strokeStyle = `hsl(210, 40%, ${lightness - 20}%)`;
hexCtx.lineWidth = 1;
hexCtx.stroke();
}
}
}
hexAnimationId = requestAnimationFrame(draw);
};
draw();
}
function stopHexGrid() {
if (hexAnimationId) {
cancelAnimationFrame(hexAnimationId);
hexAnimationId = null;
}
}
/**
* Initialize Media Player container
*/
function initMediaPlayerContainer() {
if (isMediaPlayerInitialized) {
console.log('MEDIA PLAYER: Already initialized, just showing');
showMediaPlayer();
return;
}
console.log('MEDIA PLAYER: Initializing container...');
// Find the bottom-left container
const container = document.querySelector('.lego-container[data-position="bottom-left"]');
if (!container) {
console.error('MEDIA PLAYER: Container not found');
return;
}
// Clear existing content and create structure
container.innerHTML = `
<div class="panel-header">
<div style="display: flex; justify-content: space-between; align-items: center;">
<span>MEDIA PLAYER</span>
<div style="display: flex; gap: 4px;">
<button class="media-btn" id="media-upload" title="Upload File">
<i data-lucide="folder-open" style="width: 12px; height: 12px;"></i>
</button>
<button class="media-btn" id="media-clear" title="Clear">
<i data-lucide="trash-2" style="width: 12px; height: 12px;"></i>
</button>
</div>
</div>
</div>
<div class="media-player-content">
<div class="media-drop-zone" id="media-drop-zone">
<div class="drop-zone-text">
<div class="drop-icon">
<i data-lucide="music" style="width: 24px; height: 24px;"></i>
</div>
<div class="drop-title">Drop media files here</div>
<div class="drop-subtitle">or click to browse</div>
<div class="supported-formats">MP3, MP4, WAV, AVI, MOV</div>
</div>
<input type="file" id="media-file-input" accept="audio/*,video/*" multiple style="display: none;">
</div>
<div class="media-player" id="media-player" style="display: none;">
<div class="media-info">
<div class="media-filename" id="media-filename">No file selected</div>
<div class="media-metadata" id="media-metadata"></div>
</div>
<div class="media-element-container">
<img id="media-cover-art" alt="cover" style="display:none; position:absolute; inset:0; width:100%; height:100%; object-fit: cover; z-index: 9999; pointer-events: none; opacity: 0.2;" />
<audio id="media-audio" style="display: none;"></audio>
<video id="media-video" playsinline style="display: none;"></video>
<div class="orb-visualizer-container" id="orb-visualizer-container"></div>
</div>
<div class="media-controls">
<button class="media-btn" id="media-play-pause" title="Play/Pause">
<i data-lucide="play" style="width: 12px; height: 12px;"></i>
</button>
<button class="media-btn" id="media-stop" title="Stop">
<i data-lucide="square" style="width: 12px; height: 12px;"></i>
</button>
<button class="media-btn" id="media-volume" title="Volume">
<i data-lucide="volume-2" style="width: 12px; height: 12px;"></i>
</button>
<div class="media-progress-container">
<div class="media-progress-bar" id="media-progress-bar">
<div class="media-progress-fill" id="media-progress-fill"></div>
</div>
</div>
<div class="media-time" id="media-time">00:00</div>
<button class="media-btn" id="media-video-fullscreen" title="Fullscreen video">
<i data-lucide="maximize-2" style="width: 12px; height: 12px;"></i>
</button>
</div>
<div class="hexgrid" id="hexgrid" style="display: none;"></div>
<div class="spectrogram" id="spectrogram" style="display: none;"></div>
</div>
</div>
`;
// Setup media player controls
setupMediaPlayerControls();
// Initialize Lucide icons
if (typeof lucide !== 'undefined') {
lucide.createIcons();
}
isMediaPlayerInitialized = true;
console.log('MEDIA PLAYER: Initialized successfully');
}
/**
* Setup media player controls
*/
function setupMediaPlayerControls() {
// File input
const fileInput = document.getElementById('media-file-input');
const dropZone = document.getElementById('media-drop-zone');
// Upload button
document.getElementById('media-upload').addEventListener('click', function() {
fileInput.click();
});
// Clear button
document.getElementById('media-clear').addEventListener('click', function() {
clearMediaPlayer();
});
// File input change
fileInput.addEventListener('change', function(e) {
if (e.target.files.length > 0) {
loadMediaFiles(Array.from(e.target.files));
}
});
// Drop zone events
dropZone.addEventListener('click', function() {
fileInput.click();
});
dropZone.addEventListener('dragover', function(e) {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', function(e) {
e.preventDefault();
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
dropZone.classList.remove('drag-over');
const files = Array.from(e.dataTransfer.files).filter(file =>
file.type.startsWith('audio/') || file.type.startsWith('video/')
);
if (files.length > 0) {
loadMediaFiles(files);
}
});
// Media controls
document.getElementById('media-play-pause').addEventListener('click', function() {
togglePlayPause();
});
document.getElementById('media-stop').addEventListener('click', function() {
stopMedia();
});
document.getElementById('media-volume').addEventListener('click', function() {
toggleMute();
});
// Fullscreen video button
const fsBtn = document.getElementById('media-video-fullscreen');
if (fsBtn) {
fsBtn.addEventListener('click', function() {
toggleVideoFullscreen();
});
}
// Keep icon in sync with fullscreen state
['fullscreenchange','webkitfullscreenchange','mozfullscreenchange','MSFullscreenChange']
.forEach(evt => document.addEventListener(evt, updateFullscreenIcon));
// Progress bar
const progressBar = document.getElementById('media-progress-bar');
progressBar.addEventListener('click', function(e) {
const rect = progressBar.getBoundingClientRect();
const clickX = e.clientX - rect.left;
const percentage = clickX / rect.width;
seekTo(percentage);
});
// Media element events
const audio = document.getElementById('media-audio');
const video = document.getElementById('media-video');
[audio, video].forEach(media => {
media.addEventListener('loadedmetadata', function() {
mediaDuration = media.duration;
});
media.addEventListener('timeupdate', function() {
mediaCurrentTime = media.currentTime;
updateProgress();
updateTime();
});
media.addEventListener('play', function() {
mediaIsPlaying = true;
updatePlayButton();
});
media.addEventListener('pause', function() {
mediaIsPlaying = false;
updatePlayButton();
});
media.addEventListener('ended', function() {
mediaIsPlaying = false;
updatePlayButton();
});
});
}
/**
* Load media files
*/
function loadMediaFiles(files) {
if (files.length === 0) return;
// For now, just load the first file
const file = files[0];
currentMediaFile = file;
// Create object URL
const url = URL.createObjectURL(file);
// Determine if it's audio or video
const isVideo = file.type.startsWith('video/');
const audio = document.getElementById('media-audio');
const video = document.getElementById('media-video');
// Hide drop zone, show player
document.getElementById('media-drop-zone').style.display = 'none';
document.getElementById('media-player').style.display = 'block';
// Set up the appropriate media element
if (isVideo) {
audio.style.display = 'none';
video.style.display = 'block';
video.src = url;
// Ensure native controls are hidden (we use custom controls)
video.controls = false;
// Visualizations only for audio: hide and stop if previously running
const specEl = document.getElementById('spectrogram');
const hexEl = document.getElementById('hexgrid');
if (specEl) specEl.style.display = 'none';
if (hexEl) hexEl.style.display = 'none';
stopSpectrogram();
stopHexGrid();
} else {
video.style.display = 'none';
audio.style.display = 'block';
audio.src = url;
// Ensure native controls are hidden
audio.controls = false;
// Connect audio to visualizer
connectAudioToVisualizer(audio);
// Initialize orb in media player container
initOrbInMediaPlayer();
// Show and (re)start audio-only visualizations
const specEl = document.getElementById('spectrogram');
const hexEl = document.getElementById('hexgrid');
if (specEl) specEl.style.display = 'block';
if (hexEl) hexEl.style.display = 'block';
initSpectrogram();
startSpectrogram();
initHexGrid();
startHexGrid();
}
// Update filename
document.getElementById('media-filename').textContent = file.name;
// Reset and show metadata placeholder
const metaEl = document.getElementById('media-metadata');
if (metaEl) metaEl.textContent = '';
// Extract and render metadata (tags/tech info)
extractAndDisplayMetadata({ file, url, isVideo });
console.log('MEDIA PLAYER: Loaded file:', file.name);
}
/**
* Load jsmediatags from CDN if not present
*/
function ensureJsMediaTags() {
return new Promise((resolve, reject) => {
if (window.jsmediatags) return resolve();
const existing = document.querySelector('script[data-role="jsmediatags-cdn"]');
if (existing) {
existing.addEventListener('load', () => resolve());
existing.addEventListener('error', () => reject(new Error('Failed to load jsmediatags')));
return;
}
const script = document.createElement('script');
script.src = 'https://unpkg.com/jsmediatags@3.9.7/dist/jsmediatags.min.js';
script.async = true;
script.defer = true;
script.setAttribute('data-role', 'jsmediatags-cdn');
script.onload = () => resolve();
script.onerror = () => reject(new Error('Failed to load jsmediatags'));
document.head.appendChild(script);
});
}
/**
* Extract tags/tech metadata and render it under the filename.
* Also displays MP3 cover art overlay when available.
*/
function extractAndDisplayMetadata({ file, url, isVideo }) {
const metaEl = document.getElementById('media-metadata');
if (!metaEl) return;
// Base technical info (available immediately)
const basic = [];
if (file && file.type) basic.push(`type: ${file.type}`);
if (file && Number.isFinite(file.size)) basic.push(`size: ${(file.size / (1024*1024)).toFixed(2)} MB`);
metaEl.textContent = basic.join(' • ');
// Enrich with duration/resolution when available
const audio = document.getElementById('media-audio');
const video = document.getElementById('media-video');
const media = isVideo ? video : audio;
const enrichTech = () => {
const parts = [];
if (basic.length) parts.push(basic.join(' • '));
if (!isNaN(media?.duration)) parts.push(`duration: ${formatTime(media.duration)}`);
if (isVideo && media?.videoWidth && media?.videoHeight) {
parts.push(`resolution: ${media.videoWidth}x${media.videoHeight}`);
}
metaEl.textContent = parts.join(' • ');
};
if (media) {
if (!isNaN(media.duration) && media.duration > 0) enrichTech();
media.addEventListener('loadedmetadata', enrichTech, { once: true });
}
// Audio tags (ID3) and cover art
if (!isVideo && file && file.type && file.type.startsWith('audio/')) {
ensureJsMediaTags()
.then(() => {
window.jsmediatags.read(file, {
onSuccess: ({ tags }) => {
const tagParts = [];
if (tags?.title) tagParts.push(`title: ${tags.title}`);
if (tags?.artist) tagParts.push(`artist: ${tags.artist}`);
if (tags?.album) tagParts.push(`album: ${tags.album}`);
if (tags?.year) tagParts.push(`year: ${tags.year}`);
if (tags?.track) {
const tr = typeof tags.track === 'object' ? tags.track?.toString?.() : tags.track;
if (tr) tagParts.push(`track: ${tr}`);
}
const current = metaEl.textContent ? metaEl.textContent + ' • ' : '';
if (tagParts.length) metaEl.textContent = current + tagParts.join(' • ');
// Cover art
const pic = tags?.picture || tags?.APIC;
if (pic && pic.data && pic.format) {
try {
const byteArray = (pic.data instanceof Uint8Array) ? pic.data : new Uint8Array(pic.data);
const blob = new Blob([byteArray], { type: pic.format });
const coverUrl = URL.createObjectURL(blob);
setCoverArt(coverUrl);
} catch (e) {
console.warn('MEDIA PLAYER: Failed to set cover art', e);
}
}
},
onError: (error) => {
console.warn('MEDIA PLAYER: Tag read error', error);
}
});
})
.catch(() => {
// jsmediatags failed to load; skip tag parsing silently
});
} else {
// Not audio; ensure cover art hidden
clearCoverArt();
}
}
function setCoverArt(src) {
const img = document.getElementById('media-cover-art');
if (!img) return;
img.src = src;
img.style.display = 'block';
}
function clearCoverArt() {
const img = document.getElementById('media-cover-art');
if (!img) return;
if (img.src && img.src.startsWith('blob:')) {
try { URL.revokeObjectURL(img.src); } catch(_) {}
}
img.removeAttribute('src');
img.style.display = 'none';
}
/**
* Toggle play/pause
*/
function togglePlayPause() {
const audio = document.getElementById('media-audio');
const video = document.getElementById('media-video');
const media = audio.style.display !== 'none' ? audio : video;
if (mediaIsPlaying) {
media.pause();
} else {
media.play();
}
}
/**
* Stop media
*/
function stopMedia() {
const audio = document.getElementById('media-audio');
const video = document.getElementById('media-video');
const media = audio.style.display !== 'none' ? audio : video;
media.pause();
media.currentTime = 0;
mediaIsPlaying = false;
updatePlayButton();
updateProgress();
updateTime();
// Stop visualization
stopVisualization();
// Exit video fullscreen if active
const vid = document.getElementById('media-video');
if (document.fullscreenElement === vid || document.webkitFullscreenElement === vid) {
if (document.exitFullscreen) document.exitFullscreen();
else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
}
}
/**
* Toggle mute
*/
function toggleMute() {
const audio = document.getElementById('media-audio');
const video = document.getElementById('media-video');
const media = audio.style.display !== 'none' ? audio : video;
media.muted = !media.muted;
setButtonIcon('media-volume', media.muted ? 'volume-x' : 'volume-2');
}
/**
* Seek to position
*/
function seekTo(percentage) {
const audio = document.getElementById('media-audio');
const video = document.getElementById('media-video');
const media = audio.style.display !== 'none' ? audio : video;
if (mediaDuration > 0) {
media.currentTime = mediaDuration * percentage;
}
}
/**
* Update play button
*/
function setButtonIcon(buttonId, iconName) {
const btn = document.getElementById(buttonId);
if (!btn) {
console.warn(`MEDIA PLAYER: Button ${buttonId} not found`);
return;
}
btn.innerHTML = `<i data-lucide="${iconName}" style="width: 12px; height: 12px;"></i>`;
if (typeof lucide !== 'undefined') {
lucide.createIcons();
}
}
function updatePlayButton() {
setButtonIcon('media-play-pause', mediaIsPlaying ? 'pause' : 'play');
}
function updateFullscreenIcon() {
const video = document.getElementById('media-video');
if (!video) return;
const isFs = document.fullscreenElement === video || document.webkitFullscreenElement === video;
setButtonIcon('media-video-fullscreen', isFs ? 'minimize-2' : 'maximize-2');
}
function toggleVideoFullscreen() {
const video = document.getElementById('media-video');
if (!video || video.style.display === 'none') return; // Only for visible video
const isFs = document.fullscreenElement === video || document.webkitFullscreenElement === video;
if (!isFs) {
if (video.requestFullscreen) video.requestFullscreen();
else if (video.webkitRequestFullscreen) video.webkitRequestFullscreen();
} else {
if (document.exitFullscreen) document.exitFullscreen();
else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
}
// Icon will be updated on fullscreenchange, but also update immediately
updateFullscreenIcon();
}
/**
* Update progress bar
*/
function updateProgress() {
if (mediaDuration > 0) {
const percentage = (mediaCurrentTime / mediaDuration) * 100;
document.getElementById('media-progress-fill').style.width = percentage + '%';
}
}
/**
* Update time display
*/
function updateTime() {
const timeElement = document.getElementById('media-time');
const current = formatTime(mediaCurrentTime);
const total = formatTime(mediaDuration);
timeElement.textContent = `${current} / ${total}`;
}