React
레벨 별 사운드 구현하기
한츄
2024. 4. 17. 10:11
1. 사운드기능을 하는 컴포넌트 만들기
import { useRef, useEffect } from 'react';
import { useModalStore } from '@/store/useModalStore';
export const AlarmSound: React.FC = () => {
const audioRef = useRef<HTMLAudioElement>(null);
const { play, togglePlay, alarmLevel } = useModalStore();
useEffect(() => {
let intervalId: ReturnType<typeof setInterval> | null = null;
const playAudio = () => {
if (audioRef.current) {
// 오디오 로딩 대기 후 재생
const playPromise = audioRef.current.play();
if (playPromise !== undefined) {
playPromise.then(() => {
// 재생 성공
}).catch((error) => {
console.error('오디오 재생 에러:', error);
});
}
}
};
if (play) {
playAudio(); // 초기에 한 번 재생
intervalId = setInterval(playAudio, 5000); // 5초 간격으로 재생
}
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [play]);
useEffect(() => {
// 알람 레벨에 따라 오디오 소스 변경
if (audioRef.current) {
audioRef.current.src = alarmLevel === 50 ? "/sound/alarm2.mp3" : "/sound/alarm1.mp3";
// 새로운 소스 로딩 대기 후 자동 재생 방지
audioRef.current.load();
}
}, [alarmLevel]);
return (
<>
<audio ref={audioRef} preload="auto">
<source src={alarmLevel === 50 ? "/sound/alarm2.mp3" : "/sound/alarm1.mp3"} type="audio/mp3" />
</audio>
<button
type="button"
className="ml-2 my-auto"
aria-label="play"
onClick={togglePlay}
>
{play ? '■' : '▶'}
</button>
</>
);
};
2. 트리거 해주는 부분에서 alarmLevel을 업데이트
import { AlarmSound } from './AlarmSound';
const ModalComponent: React.FC = () => {
useEffect(() => {
// 나머지 코드 생략
setAlarmLevel(twoDayIssueList[0]?.level)
}, [groupedMessages,twoDayIssueList]);
3. 나머지 코드들은 기존 코드를 유지