death-sound.tsx 1.2 KB

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