Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactor] 레이싱 게임 오디오 로직을 useRacingGameAudio 커스텀 훅으로 리팩토링 #52

Merged
merged 2 commits into from
Aug 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions Caecae/src/hooks/useRacingGameAudio.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { useRef, useEffect } from "react";

const useRacingGameAudio = (playingAudioSrc: string, stopAudioSrc: string) => {
const playingAudioRef = useRef<HTMLAudioElement | null>(null);
const stoppingAudioRef = useRef<HTMLAudioElement | null>(null);
const stoppingAudioRunRef = useRef<boolean>(false);

useEffect(() => {
playingAudioRef.current = new Audio(playingAudioSrc);
stoppingAudioRef.current = new Audio(stopAudioSrc);

return () => {
resetAudio(playingAudioRef.current);
resetAudio(stoppingAudioRef.current);
};
}, [playingAudioSrc, stopAudioSrc]);

const playAudio = (audio: HTMLAudioElement | null) => {
if (audio) {
resetAudio(audio);
const playPromise = audio.play();
if (playPromise !== undefined) {
playPromise.catch((error) => {
console.error("Audio play error:", error);
});
}
}
};

const resetAudio = (audio: HTMLAudioElement | null) => {
if (audio) {
audio.pause();
audio.currentTime = 0;
audio.volume = 1.0;
audio.load();
}
};

const fadeOutAudio = (
audio: HTMLAudioElement | null,
duration: number,
callback: () => void
) => {
if (!audio) return;

const step = 0.1;
const fadeInterval = duration / (audio.volume / step);

const fade = setInterval(() => {
if (audio.volume > step) {
audio.volume -= step;
}else {
clearInterval(fade);
audio.volume = 0;
audio.pause();
callback();
}
}, fadeInterval);
};

return {
startPlayingAudio: () => {
playAudio(playingAudioRef.current);
},
startStoppingAudio: () => {
if (!stoppingAudioRunRef.current) {
stoppingAudioRunRef.current = true;
playAudio(stoppingAudioRef.current);
}
},
fadeOutPlayingAudio: (duration: number, callback: () => void) => {
fadeOutAudio(playingAudioRef.current, duration, callback);
},
resetAllAudio: () => {
resetAudio(playingAudioRef.current);
resetAudio(stoppingAudioRef.current);
},
stoppingAudioRunRef
};
};

export default useRacingGameAudio;
Loading