joshwcomeau / use-sound

A React Hook for playing sound effects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't stop the audio when the component unmounts.

swastikpatro opened this issue · comments

I'm using use-sound in Vite project.

import useSound from 'use-sound';
import { DependencyList, useEffect, useRef, useState } from 'react';

const useAudio = (audioTrack: string, dependency: DependencyList) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [play, { pause, stop }] = useSound(audioTrack, {
    volume: 1,
    onend: () => stopPlayer(),
  });

  useEffect(() => {
    stopPlayer();
  }, dependency);

  useEffect(() => {
    return () => {
      // this can't stop the audio.
      stopPlayer();
    };
  }, []);

  const stopPlayer = () => {
    setIsPlaying(false);
    stop();
  };

  const handleSoundPausePlay = () => {
    setIsPlaying(!isPlaying);

    if (isPlaying) {
      pause();
      return;
    }

    play();
  };

  return { isPlaying, handleSoundPausePlay, stopPlayer };
};

Can't stop the Audio, when the component unmounts. Need help with this.

This is an issue even when using a cleanup on useEffect