useSoundNotification.ts 727 B

1234567891011121314151617181920212223242526272829303132
  1. import { useEffect, useRef } from "react";
  2. import { playNotificationSound } from "@/utils/sound";
  3. export function useSoundNotification(enabled: boolean = true) {
  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 = () => {
  19. if (enabled && audioRef.current) {
  20. audioRef.current.play().catch(() => {
  21. // 忽略播放错误
  22. });
  23. }
  24. };
  25. return { play };
  26. }