Is it good to implement audio autoplay to prevent DOMException when user didn't interact the web first

104 Views Asked by At

I find the way to autoplay the audio by trying to mute the audio first then play the audio and unmute it, but didn't work, it's show an error as below

DOMException: play() failed because the user didn't interact with the document first

Finally, I implement the autoplay by using listener to catch whether the user is click the browser's screen area then autoplay the audio without any error and successfully autoplayed.

Is it good to implement audio autoplay like this?

const SoundBar = ({ autoPlay = false }) => {
  const ref = useRef();
  const [playing, setPlaying] = useState(false);

  useEffect(() => {
    let clicked = 0;
    const handleAutoplay = () => {
      if (autoPlay && !playing && !(clicked > 0)) {
        ref.current.play();
        setPlaying(true);
        clicked++;
      }
    };
    window.addEventListener("click", handleAutoplay);
    return () => window.removeEventListener("click", handleAutoplay);
  }, []);

  const handlePlaying = () => {
    const p = !playing;
    p ? ref.current.play() : ref.current.pause();
    setPlaying(p);
  };

  return (
    <Box onClick={() => handlePlaying()}>
      <Line playing={playing} />
      <Line playing={playing} />
      <Line playing={playing} />
      <Line playing={playing} />
      <Line playing={playing} />
      <audio src={music} ref={ref} loop />
    </Box>
  );
};

0

There are 0 best solutions below