File size: 16,938 Bytes
21986a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f57be92
 
 
ba6c831
f57be92
ba6c831
 
 
 
b615593
 
21986a1
ba6c831
21986a1
 
 
 
 
 
 
 
 
 
 
 
 
ba6c831
 
f57be92
 
 
 
 
 
 
ba6c831
f57be92
 
 
 
 
ffc893c
f57be92
 
ba6c831
f57be92
 
ba6c831
 
 
f57be92
 
 
 
ba6c831
f57be92
 
 
 
ba6c831
f57be92
 
 
 
ba6c831
f57be92
21986a1
ba6c831
 
 
 
 
 
 
 
 
21986a1
 
 
f57be92
ba6c831
f57be92
 
ba6c831
 
 
 
 
 
 
 
 
f57be92
 
 
 
ba6c831
f57be92
 
ba6c831
f57be92
 
ba6c831
21986a1
f57be92
 
21986a1
f57be92
ba6c831
21986a1
 
 
 
 
ba6c831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f57be92
ba6c831
21986a1
 
 
 
 
 
 
ba6c831
21986a1
 
ba6c831
21986a1
 
 
 
 
 
 
 
 
 
ba6c831
21986a1
 
ba6c831
21986a1
f57be92
ba6c831
21986a1
 
 
 
 
 
ba6c831
21986a1
 
 
 
 
 
 
 
 
ba6c831
21986a1
 
 
ba6c831
21986a1
 
 
 
 
ba6c831
21986a1
 
 
 
 
ba6c831
21986a1
 
 
 
 
ba6c831
21986a1
 
ba6c831
21986a1
 
f57be92
ba6c831
f57be92
 
 
 
 
 
 
 
 
93b25cc
f57be92
 
21986a1
 
ba6c831
21986a1
 
 
 
 
 
 
 
 
 
ba6c831
21986a1
 
 
 
 
 
 
 
ba6c831
21986a1
 
 
 
 
 
 
 
ba6c831
21986a1
 
 
ba6c831
b615593
 
 
 
21986a1
ba6c831
21986a1
 
 
 
 
 
 
 
 
 
 
 
93b25cc
f57be92
93b25cc
 
 
 
21986a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93b25cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba6c831
93b25cc
ba6c831
93b25cc
 
 
21986a1
93b25cc
ba6c831
93b25cc
ba6c831
93b25cc
 
21986a1
93b25cc
 
 
b615593
 
93b25cc
 
 
 
 
b615593
93b25cc
 
 
 
 
 
21986a1
93b25cc
 
21986a1
93b25cc
 
 
 
 
21986a1
93b25cc
21986a1
 
 
 
93b25cc
21986a1
 
 
ba6c831
21986a1
 
 
93b25cc
21986a1
 
 
 
f57be92
21986a1
 
 
 
 
ba6c831
 
 
 
 
 
 
 
21986a1
 
 
 
 
 
 
 
 
ba6c831
 
 
 
 
 
 
 
21986a1
 
 
93b25cc
 
96b94b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b615593
 
 
 
 
 
 
 
 
 
 
 
21986a1
 
 
 
 
 
 
93b25cc
 
 
 
21986a1
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect, useRef } from "react";
import "./MusicPlayer.css";
import { useMusicPlayer } from "@/context/MusicPlayerContext";
import { IoPlayOutline, IoPauseOutline } from "react-icons/io5";
import { IoIosArrowDown, IoIosArrowUp } from "react-icons/io";
import {
  TbRewindBackward5,
  TbRewindForward5,
  TbPlayerStop,
  TbVolumeOff,
  TbVolume,
  TbPlayerSkipBack,
  TbPlayerSkipForward,
  TbPlaylist,
  TbPlaylistOff,
} from "react-icons/tb";
import { RiFullscreenLine, RiFullscreenExitLine } from "react-icons/ri";
import { formatTime } from "./utils";

export default function MusicPlayer() {
  const {
    videoRef,
    isPlayerVisible,
    src,
    isPlayerMaximized,
    togglePlayerSize,
    setIsPlayerVisible,
    initializePlayer,
    title,
    setNowPlaying,
    nowPlaying,
    didDestroy,
    setDidDestroy,
    playNext,
    playPrevious,
    canPlayPrevious,
    canPlayNext,
    isPlayEueOpen,
    setIsPlayEueOpen,
  } = useMusicPlayer();

  const [currentSrc, setCurrentSrc] = useState(src);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [progress, setProgress] = useState(0);
  const [bufferProgress, setBufferProgress] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [showControls, setShowControls] = useState(true);
  const [isBuffering, setIsBuffering] = useState(true);
  const [volume, setVolume] = useState(1);
  const [isMuted, setIsMuted] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const overlayTimeout = useRef(null);
  const seekTime = 5;
  const poster = "https://dlcdnwebimgs.asus.com/gain/4BB18AEF-347E-4DB6-B78C-C0FFE1F20385/w750/h470"

  // Event Handlers
  const handleTimeUpdate = (videoElement) => {
    if (videoElement) {
      setCurrentTime(videoElement.currentTime);
      setProgress((videoElement.currentTime / videoElement.duration) * 100);
    }
  };

  const handleLoadedMetadata = (videoElement) => {
    if (videoElement) {
      setDuration(videoElement.duration);
      setProgress(0);
      setCurrentTime(0);
      videoElement.play();
    }
  };

  const handleProgress = (videoElement) => {
    if (videoElement && videoElement.buffered.length > 0) {
      const bufferEnd = videoElement.buffered.end(
        videoElement.buffered.length - 1
      );
      const bufferValue = (bufferEnd / videoElement.duration) * 100;
      setBufferProgress(bufferValue);
    }
  };

  const handlePlay = () => {
    setIsPlaying(true);
    setNowPlaying(title);
  };

  const handlePause = () => {
    setIsPlaying(false);
    setNowPlaying("");
  };

  const attachEventListeners = (videoElement) => {
    if (videoElement) {
      videoElement.addEventListener("timeupdate", () =>
        handleTimeUpdate(videoElement)
      );
      videoElement.addEventListener("loadedmetadata", () =>
        handleLoadedMetadata(videoElement)
      );
      videoElement.addEventListener("progress", () =>
        handleProgress(videoElement)
      );
      videoElement.addEventListener("play", handlePlay);
      videoElement.addEventListener("pause", handlePause);
    }
  };

  const detachEventListeners = (videoElement) => {
    if (videoElement) {
      videoElement.removeEventListener("timeupdate", () =>
        handleTimeUpdate(videoElement)
      );
      videoElement.removeEventListener("loadedmetadata", () =>
        handleLoadedMetadata(videoElement)
      );
      videoElement.removeEventListener("progress", () =>
        handleProgress(videoElement)
      );
      videoElement.removeEventListener("play", handlePlay);
      videoElement.removeEventListener("pause", handlePause);
    }
  };

  useEffect(() => {
    const videoElement = videoRef.current;

    // Attach event listeners
    attachEventListeners(videoElement);

    return () => {
      // Detach event listeners
      detachEventListeners(videoElement);
    };
  }, [videoRef, currentSrc, nowPlaying, didDestroy]);

  useEffect(() => {
    if (src !== currentSrc) {
      setCurrentSrc(src);
    }
  }, [src, currentSrc]);

  useEffect(() => {
    if ('mediaSession' in navigator) {
      navigator.mediaSession.metadata = new MediaMetadata({
        title: title,
        artwork: [
          { src: poster } // Ensure 'poster' is defined in your component
        ]
      });
  
      navigator.mediaSession.setActionHandler('play', () => {
        videoRef.current.play();
      });
  
      navigator.mediaSession.setActionHandler('pause', () => {
        videoRef.current.pause();
      });
  
      navigator.mediaSession.setActionHandler('seekbackward', (details) => {
        videoRef.current.currentTime = Math.max(videoRef.current.currentTime - (details.seekOffset || 10), 0);
      });
  
      navigator.mediaSession.setActionHandler('seekforward', (details) => {
        videoRef.current.currentTime = Math.min(videoRef.current.currentTime + (details.seekOffset || 10), videoRef.current.duration);
      });
  
      navigator.mediaSession.setActionHandler('stop', () => {
        destroyPlayer();
      });
  
      // New action handlers for previous and next
      navigator.mediaSession.setActionHandler('previoustrack', () => {
        playPrevious(); // Assuming playPrevious is a function that plays the previous track
      });
  
      navigator.mediaSession.setActionHandler('nexttrack', () => {
        playNext(); // Assuming playNext is a function that plays the next track
      });
    }
  
    // Cleanup function to reset media session when component unmounts
    return () => {
      if ('mediaSession' in navigator) {
        navigator.mediaSession.metadata = null;
        navigator.mediaSession.setActionHandler('play', null);
        navigator.mediaSession.setActionHandler('pause', null);
        navigator.mediaSession.setActionHandler('seekbackward', null);
        navigator.mediaSession.setActionHandler('seekforward', null);
        navigator.mediaSession.setActionHandler('stop', null);
        navigator.mediaSession.setActionHandler('previoustrack', null);
        navigator.mediaSession.setActionHandler('nexttrack', null);
      }
    };
  }, [title, poster, playPrevious, playNext]);
  

  useEffect(() => {
    if (showControls) {
      if (overlayTimeout.current) {
        clearTimeout(overlayTimeout.current);
      }
      overlayTimeout.current = setTimeout(() => setShowControls(false), 3000);
    }

    return () => clearTimeout(overlayTimeout.current);
  }, [showControls]);

  const togglePlayPause = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const handleVolumeChange = (event) => {
    let volumeValue = parseFloat(event.target.value);

    // Ensure the volume is a finite number between 0 and 1
    volumeValue = Math.max(0, Math.min(1, volumeValue));

    setVolume(volumeValue);
    if (videoRef.current) {
      videoRef.current.volume = volumeValue;
    }
    setIsMuted(volumeValue === 0);
  };

  const toggleMute = () => {
    if (isMuted) {
      videoRef.current.volume = volume;
      setIsMuted(false);
    } else {
      videoRef.current.volume = 0;
      setIsMuted(true);
    }
  };

  const toggleFullscreen = () => {
    const doc = window.document;
    const docEl = doc.documentElement;

    const requestFullscreen =
      docEl.requestFullscreen ||
      docEl.mozRequestFullScreen ||
      docEl.webkitRequestFullscreen ||
      docEl.msRequestFullscreen;

    const exitFullscreen =
      doc.exitFullscreen ||
      doc.mozCancelFullScreen ||
      docEl.webkitExitFullscreen ||
      doc.msExitFullscreen;

    if (!isFullscreen) {
      requestFullscreen.call(docEl);
    } else {
      exitFullscreen.call(doc);
    }

    setIsFullscreen(!isFullscreen);
  };

  const destroyPlayer = () => {
    if (videoRef.current) {
      videoRef.current.pause();
      videoRef.current.currentTime = 0;
      videoRef.current.removeAttribute("src"); // Clear the source
      videoRef.current.load(); // Reload to reset duration/currentTime
      setNowPlaying("");
      setCurrentSrc("/reset");
      setCurrentTime(0);
      setDuration(0);
      setProgress(0);
      setBufferProgress(0);
      setIsPlaying(false);
      setIsPlayerVisible(false);
      setDidDestroy(true);
      console.log("setting didDestroy to true");
    }
  };

  const handleProgressClick = (e) => {
    const progressBar = e.currentTarget;
    const rect = progressBar.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const newTime = (clickX / rect.width) * duration;
    if (videoRef.current) {
      videoRef.current.currentTime = newTime;
      setCurrentTime(newTime);
    }
  };

  const handleFastForward = () => {
    if (videoRef.current) {
      videoRef.current.currentTime = Math.min(
        videoRef.current.duration,
        videoRef.current.currentTime + seekTime
      );
    }
  };

  const handleRewind = () => {
    if (videoRef.current) {
      videoRef.current.currentTime = Math.max(
        0,
        videoRef.current.currentTime - seekTime
      );
    }
  };

  const handleMouseMove = () => {
    setShowControls(true);
  };

  const handleIsPlayQueueOpen = () =>{
    setIsPlayEueOpen(!isPlayEueOpen);
  };

  if (!isPlayerVisible || !currentSrc) return null;

  return (
    <div
      className={
        isPlayerMaximized
          ? "player-maximized relative"
          : "player-minimized relative"
      }
      onMouseMove={handleMouseMove}
    >
      {isPlayerMaximized && (
        <div className={`player-controls ${showControls ? "show" : "hide"}`}>
          <div className="player-controls-top">
            <div className="name-container">
              <label className="music-title">{title}</label>
              <button className="player-max-button" onClick={togglePlayerSize}>
                <IoIosArrowDown />
              </button>
            </div>
          </div>
          <div className="player-controls-center">
            <button className="player-max-button" onClick={handleRewind}>
              <TbRewindBackward5 />
            </button>
            <button className="player-max-button" onClick={togglePlayPause}>
              {isPlaying ? <IoPauseOutline /> : <IoPlayOutline />}
            </button>
            <button className="player-max-button" onClick={handleFastForward}>
              <TbRewindForward5 />
            </button>
          </div>
          <div className="player-controls-bottom">
            <div className="player-control-bottom-top">
              <label className="current-time">{formatTime(currentTime)}</label>
              <div
                className="progress-bar-container"
                onClick={handleProgressClick}
              >
                <div
                  className="buffer-bar"
                  style={{ width: `${bufferProgress}%` }}
                />
                <div
                  className="progress-bar"
                  style={{ width: `${progress}%` }}
                />
              </div>
              <label className="duration">{formatTime(duration)}</label>
            </div>
            <div className="player-controls-down">
              <div className="player-controls-left">
                <button
                  onClick={toggleMute}
                  className="player-min-button volumn-btn"
                >
                  {isMuted ? <TbVolumeOff /> : <TbVolume />}
                </button>
                <input
                  type="range"
                  className="volume-control"
                  min="0"
                  max="1"
                  step="0.01"
                  value={volume}
                  onChange={handleVolumeChange}
                />
                <button
                  onClick={playPrevious}
                  className="previous-btn player-min-button"
                  disabled={!canPlayPrevious}
                >
                  <TbPlayerSkipBack />
                </button>

                <button
                  onClick={playNext}
                  className="next-btn player-min-button"
                  disabled={!canPlayNext}
                >
                  <TbPlayerSkipForward />
                </button>
                <button className="player-min-button" onClick={destroyPlayer}>
                  <TbPlayerStop />
                </button>
                {isPlayEueOpen ? (
                  <button className="playlist-btn player-min-button" onClick={handleIsPlayQueueOpen}>
                    <TbPlaylist />
                  </button>
                ) : (
                  <button
                    className="playlist-btn player-min-button"
                    onClick={handleIsPlayQueueOpen}
                  >
                    <TbPlaylistOff />
                  </button>
                )}
              </div>
              <div className="player-controls-right">
                <button
                  onClick={toggleFullscreen}
                  className="player-min-button"
                >
                  {isFullscreen ? (
                    <RiFullscreenExitLine />
                  ) : (
                    <RiFullscreenLine />
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
      <div className="player-top">
        <video
          ref={videoRef}
          src={currentSrc}
          poster={poster}
          preload="metadata"
          className="video-element"
          autoPlay
          onClick={isPlayerMaximized ? null : togglePlayerSize}
        />
        {!isPlayerMaximized && (
          <div className="player-controls-mini">
            <div className="player-mini-control-top">
              <label className="music-title player-mini">{title}</label>
              <button className="player-min-button" onClick={togglePlayerSize}>
                <IoIosArrowUp />
              </button>
            </div>
            <div className="player-mini-control-center">
            <button
                  onClick={playPrevious}
                  className="previous-btn player-min-button"
                  disabled={!canPlayPrevious}
                >
                  <TbPlayerSkipBack />
                </button>

              <button className="player-min-button" onClick={handleRewind}>
                <TbRewindBackward5 />
              </button>
              <button className="player-min-button" onClick={togglePlayPause}>
                {isPlaying ? <IoPauseOutline /> : <IoPlayOutline />}
              </button>
              <button className="player-min-button" onClick={handleFastForward}>
                <TbRewindForward5 />
              </button>

                <button
                  onClick={playNext}
                  className="next-btn player-min-button"
                  disabled={!canPlayNext}
                >
                  <TbPlayerSkipForward />
                </button>
              <button className="player-min-button" onClick={destroyPlayer}>
                <TbPlayerStop />
              </button>
            </div>
            <div className="player-mini-volume">
              <button
                onClick={toggleMute}
                className="player-min-button volumn-btn"
              >
                {isMuted ? <TbVolumeOff /> : <TbVolume />}
              </button>
              <input
                type="range"
                className="volume-control"
                min="0"
                max="1"
                step="0.01"
                value={volume}
                onChange={handleVolumeChange}
              />
                              {isPlayEueOpen ? (
                  <button className="playlist-btn player-min-button" onClick={handleIsPlayQueueOpen}>
                    <TbPlaylist />
                  </button>
                ) : (
                  <button
                    className="playlist-btn player-min-button"
                    onClick={handleIsPlayQueueOpen}
                  >
                    <TbPlaylistOff />
                  </button>
                )}
            </div>
          </div>
        )}
      </div>
      {!isPlayerMaximized && (
        <div className="player-mini-control-bottom">
          <label className="current-time">{formatTime(currentTime)}</label>
          <div
            className="progress-bar-container player-mini"
            onClick={handleProgressClick}
          >
            <div
              className="buffer-bar"
              style={{ width: `${bufferProgress}%` }}
            />
            <div className="progress-bar" style={{ width: `${progress}%` }} />
          </div>
          <label className="duration">{formatTime(duration)}</label>
        </div>
      )}
    </div>
  );
}