Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.9 kB
3
Indexable
Never
import VolumeOffIcon from "@mui/icons-material/VolumeOff";
import VolumeUpIcon from "@mui/icons-material/VolumeUp";
import { Button } from "@mui/material";

import React, { useEffect, useLayoutEffect, useRef, useState } from "react";

type PlayerType = {
  url: string;
};

const Player: React.FC<PlayerType> = ({ url }) => {
  const refAudio = useRef<HTMLAudioElement | null>(null);
  const refIsAudioPlay = useRef<true | false>(false);
  const [isPlaying, setIsPlaying] = useState(false);

  const toggle = () => {
    setIsPlaying(!isPlaying);
  };

  useEffect(() => {
    isPlaying ? refAudio.current?.play() : refAudio.current?.pause();
    if (isPlaying) {
      refIsAudioPlay.current = true;
    } else {
      refIsAudioPlay.current = false;
    }
  }, [isPlaying]);

  useLayoutEffect(() => {
    refAudio.current = new Audio(url);
    const handleEnded = () => refAudio.current?.play();
    const handleVisibilitychange = () => {
      if (document.hidden) {
        refAudio.current?.pause();
      } else {
        refIsAudioPlay.current ? refAudio.current?.play() : refAudio.current?.pause();
      }
    };

    refAudio.current?.addEventListener("ended", handleEnded);
    document.addEventListener("visibilitychange", handleVisibilitychange);

    return () => {
      refAudio.current?.pause();
      refAudio.current = null;
      document.removeEventListener("visibilitychange", handleVisibilitychange);
    };
  }, []);

  return (
    <Button
      variant="contained"
      sx={{ position: "absolute", top: "10px", left: "85px", zIndex: "1" }}
      onClick={toggle}
    >
      {isPlaying ? <VolumeUpIcon /> : <VolumeOffIcon />}
    </Button>
  );
};

export default Player;

// How to use:
// import Player from "../player/player";

// <Player url={"https://uno-group.hb.bizmrg.com/Blank_Jones_-_Sunny_Life_74528962.mp3"}/>