damage-sound.tsx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use client";
  2. import { useEffect, useRef, useState } from "react";
  3. import { useEditorStore } from "@/lib/store";
  4. const DAMAGE_SOUND_URL =
  5. "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/hit-OaUo19QcLdyFfqy5SMfEWyAF3ZgyxR.mp3";
  6. export function DamageSound() {
  7. const isPlaying = useEditorStore((s) => s.isPlaying);
  8. const lastDamageTime = useEditorStore((s) => s.lastDamageTime);
  9. const health = useEditorStore((s) => s.health);
  10. const audioRef = useRef<HTMLAudioElement | null>(null);
  11. const lastPlayedRef = useRef<number>(0);
  12. const [loaded, setLoaded] = useState(false);
  13. useEffect(() => {
  14. const audio = new Audio();
  15. audio.src = DAMAGE_SOUND_URL;
  16. audio.preload = "auto";
  17. audio.addEventListener("canplaythrough", () => setLoaded(true));
  18. audio.addEventListener("error", () => setLoaded(false));
  19. audioRef.current = audio;
  20. return () => {
  21. audio.pause();
  22. audio.src = "";
  23. };
  24. }, []);
  25. useEffect(() => {
  26. if (!isPlaying || !lastDamageTime || health <= 0 || !loaded) return;
  27. const now = Date.now();
  28. if (now - lastPlayedRef.current < 300) return;
  29. lastPlayedRef.current = now;
  30. if (audioRef.current) {
  31. audioRef.current.currentTime = 0;
  32. audioRef.current.volume = 0.5;
  33. audioRef.current.play().catch(() => {});
  34. }
  35. }, [isPlaying, lastDamageTime, health, loaded]);
  36. return null;
  37. }