Дополнительные поправки по событийным звукам

This commit is contained in:
RoyceDa
2026-03-18 18:28:10 +02:00
parent 88288317ab
commit 41d7a89830
2 changed files with 81 additions and 0 deletions

78
app/hooks/useSound.ts Normal file
View File

@@ -0,0 +1,78 @@
import { useRef } from "react";
export function useSound() {
const audioRef = useRef<HTMLAudioElement | null>(null);
const loopingAudioRef = useRef<HTMLAudioElement | null>(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
}
}

View File

@@ -13,5 +13,8 @@ declare global {
downloadsPath: string;
deviceName: string;
deviceId: string;
mediaApi: {
getSoundUrl: (fileName: string) => string;
};
}
}