Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't stop the audio when the component unmounts. #140

Open
swastikpatro opened this issue Dec 8, 2023 · 4 comments
Open

Can't stop the audio when the component unmounts. #140

swastikpatro opened this issue Dec 8, 2023 · 4 comments

Comments

@swastikpatro
Copy link

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.

@alyn3d
Copy link

alyn3d commented Dec 20, 2023

This is an issue even when using a cleanup on useEffect

@Benjythebee
Copy link

(2024) same;

I think this might be an issue at the Howler.js level; For some reason it feels like JS loses reference to the sound

@MaxdeoxiS
Copy link

Same issue here

@heecheon92
Copy link

Same issue, I decided not to use this lib but instead make very simple react component.

"use client";

import { useEffect, useRef } from "react";

/**
 *  How to gain autoplay access.
 *  https://championcr.com/topic/enable-auto-play/#:~:text=Mac%2C%20and%20Firefox.-,Google%20Chrome,)%E2%80%9D%20to%20%E2%80%9CAllow%E2%80%9C
 */

export function AudioAutoPlayer({
  src,
  enabled,
  loop = true,
}: {
  src: string;
  enabled: boolean;
  loop?: boolean;
}) {
  const audioRef = useRef<HTMLAudioElement>(null);

  useEffect(() => {
    if (audioRef.current) {
      if (enabled) {
        audioRef.current.play();
      } else {
        audioRef.current.pause();
      }
    }

    return () => {
      if (audioRef.current) audioRef.current.pause();
    };
  }, [enabled]);

  return <audio ref={audioRef} src={src} autoPlay={enabled} loop={loop} />;
}

Above code works just as much as I need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants