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; + }; } }