From 41d7a898306e804fd8e411ebf73d7a0a8e473580 Mon Sep 17 00:00:00 2001 From: RoyceDa Date: Wed, 18 Mar 2026 18:28:10 +0200 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=BF=D0=BE=D0=BB=D0=BD=D0=B8?= =?UTF-8?q?=D1=82=D0=B5=D0=BB=D1=8C=D0=BD=D1=8B=D0=B5=20=D0=BF=D0=BE=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D0=BF=D0=BE=20=D1=81=D0=BE?= =?UTF-8?q?=D0=B1=D1=8B=D1=82=D0=B8=D0=B9=D0=BD=D1=8B=D0=BC=20=D0=B7=D0=B2?= =?UTF-8?q?=D1=83=D0=BA=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/hooks/useSound.ts | 78 ++++++++++++++++++++++++++++++++++++++++++ lib/preload/index.d.ts | 3 ++ 2 files changed, 81 insertions(+) create mode 100644 app/hooks/useSound.ts diff --git a/app/hooks/useSound.ts b/app/hooks/useSound.ts new file mode 100644 index 0000000..44ffac8 --- /dev/null +++ b/app/hooks/useSound.ts @@ -0,0 +1,78 @@ +import { useRef } from "react"; + +export function useSound() { + const audioRef = useRef(null); + const loopingAudioRef = useRef(null); + + const stopSound = () => { + if (!audioRef.current) { + return; + } + audioRef.current.pause(); + audioRef.current.currentTime = 0; + audioRef.current.removeAttribute("src"); + audioRef.current.load(); + }; + + const playSound = (sound : string, loop: boolean = false) => { + try { + if(loop){ + if (!loopingAudioRef.current) { + loopingAudioRef.current = new Audio(); + loopingAudioRef.current.volume = 0.1; + loopingAudioRef.current.preload = "auto"; + loopingAudioRef.current.loop = true; + } + + const url = window.mediaApi.getSoundUrl(sound); + const player = loopingAudioRef.current; + + player.src = url; + const playPromise = player.play(); + if (playPromise) { + void playPromise.catch((e) => { + console.error("Failed to play looping UI sound:", e); + }); + } + return; + } + if (!audioRef.current) { + audioRef.current = new Audio(); + audioRef.current.volume = 0.1; + audioRef.current.preload = "auto"; + audioRef.current.loop = loop; + } + + const url = window.mediaApi.getSoundUrl(sound); + const player = audioRef.current; + + stopSound(); + + player.src = url; + const playPromise = player.play(); + if (playPromise) { + void playPromise.catch((e) => { + console.error("Failed to play UI sound:", e); + }); + } + } catch (e) { + console.error("Failed to prepare UI sound:", e); + } + } + + const stopLoopSound = () => { + if (!loopingAudioRef.current) { + return; + } + loopingAudioRef.current.pause(); + loopingAudioRef.current.currentTime = 0; + loopingAudioRef.current.removeAttribute("src"); + loopingAudioRef.current.load(); + } + + return { + playSound, + stopSound, + stopLoopSound + } +} \ No newline at end of file diff --git a/lib/preload/index.d.ts b/lib/preload/index.d.ts index 35fa486..284361b 100644 --- a/lib/preload/index.d.ts +++ b/lib/preload/index.d.ts @@ -13,5 +13,8 @@ declare global { downloadsPath: string; deviceName: string; deviceId: string; + mediaApi: { + getSoundUrl: (fileName: string) => string; + }; } }