useSoundNotification.ts 882 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { useCallback, useEffect, useRef, useState } from "react";
  2. export function useSoundNotification(initialEnabled: boolean = true) {
  3. const [enabled, setEnabled] = useState(initialEnabled);
  4. const audioRef = useRef<HTMLAudioElement | null>(null);
  5. useEffect(() => {
  6. if (!enabled) return;
  7. if (!audioRef.current) {
  8. audioRef.current = new Audio("/notification.mp3");
  9. audioRef.current.volume = 0.5;
  10. }
  11. return () => {
  12. if (audioRef.current) {
  13. audioRef.current.pause();
  14. audioRef.current = null;
  15. }
  16. };
  17. }, [enabled]);
  18. const play = useCallback(() => {
  19. if (enabled && audioRef.current) {
  20. audioRef.current.play().catch(() => {
  21. // 忽略播放错误
  22. });
  23. }
  24. }, [enabled]);
  25. const toggle = useCallback(() => {
  26. setEnabled((prev) => !prev);
  27. }, []);
  28. return { enabled, toggle, play };
  29. }