[ React ] ์์ด์ฝ ๋๋ฅด๋ฉด ์์ ์ฌ์๋๋ ๊ธฐ๋ฅ
์ฌ์ด๋ ํ๋ก์ ํธ ์ค, ์์ด์ฝ์ ๋๋ฅด๋ฉด ์์ ์ด ์ฌ์๋๋ ๊ธฐ๋ฅ์ด ํ์ํ๋ค.
Off ์์ด์ฝ์ผ๋ก ๋ณด์ด๋ฉด ์์ ์ด ๊บผ์ ธ์๋ค๋ ๊ฒ์ด๊ณ ,
Up ์์ด์ฝ์ผ๋ก ๋ณด์ด๋ฉด ์์ ์ด ์คํ์ค์ด๋ผ๋ ๋ป์ด๋ค.
์ด ๋ ์์ด์ฝ์ mui์์ ๊ฐ์ ธ์๋ค.
const [isPlay, setIsPlay] = useState<boolean>(false);
const audio = new Audio(music);
const onClickVolume = () => {
// ์ฌ์ ์ค
if (isPlay) {
audio.pause();
setIsPlay(false);
} else {
audio.play();
setIsPlay(true);
}
};
1. ์ฒซ ๋ฒ์งธ ์ค๋ฅ
Cannot find module 'mp3 ๊ฒฝ๋ก' or its corresponding type declarations.
How to fix the Cannot find module mp3 file or its corresponding type declarations
How to fix the error Cannot find module './audio/audio1.mp3' or its corresponding type declarations. also already use the require('./audio/audio1.mp3') and also getting an error.
stackoverflow.com
src/react-app-env.d.ts
์ด ํ์ผ์ ์ถ๊ฐํด์ฃผ๋ ์ ์์ ์ผ๋ก ์ฌ์์ด ๋์๋ค.
declare module '*.mp3'
2. ์ค์ง๊ฐ ์ ๋จ
pause๊ฐ ์ ๋๋ก ๋จน์ง ์๋ ์ค๋ฅ๊ฐ ์์๋ค. ์ค์งํ๋ ์๋ฏธ์ ์์ด์ฝ์ ๋๋ ๋ค๊ฐ ๋ค์ ์ฌ์์์ด์ฝ์ ๋๋ฅด์ ์์ ์ด ๊ฒน์ฌ์๋๋ ์ด์๋ ์์๋ค. ์์ ์ ์นด์นด์ค๋งต API ์ฐ๊ฒฐํ ๋๋ ๋น์ทํ ์ด์๊ฐ ์์๋ค. ์ด๊ธฐ ๋ ๋๋ง๊ณผ ์ธ๋ง์ดํธ์ ๋ฆฌ์ค๋ ์ ๋ฆฌ ๋ฑ์ ํด์ฃผ์ด์ผ ํ๋ค.
const [audio] = useState(new Audio(music)); // audio ๊ฐ์ฒด ์์ฑ
useEffect(() => {
const handleEnded = () => {
// ์์
์ด ๋๋ฌ์ ๋ ํ ์์
setIsPlay(false);
};
audio.addEventListener("ended", handleEnded);
// ์ธ๋ง์ดํธ ์ ์ด๋ฒคํธ ๋ฆฌ์ค๋ ์ ๋ฆฌ
return () => {
audio.removeEventListener("ended", handleEnded);
};
}, [audio]);
์ด๋ฐ์์ผ๋ก ์์ฑํด์ฃผ๋ฉด ํด๊ฒฐ์ด ๋๋ค. ๊ทธ๋ฐ๋ฐ.. React ์ค๋ฌ์ด ์ฝ๋๋ ์๋๋ผ๋ ์๊ฐ์ด ๋ค์๋ค.
๋ฆฌ์กํธ ์ค๋์ค ์ปดํฌ๋ํธ ๋ง๋ค๊ธฐ with ํ์ ์คํฌ๋ฆฝํธ & ๋ฆฌ์ฝ์ผ
my-app ์ด๋ ์ด๋ฆ์ ํ์ ์คํฌ๋ฆฝํธ๊ธฐ๋ฐ ํ๋ก์ ํธ ์์ฑnpx create-react-app my-app --template typescript๋ฆฌ์ฝ์ผ ์ค์นnpm install recoil์ค๋์ค ํ์ผ์ ๋ค๊ณ ์ค๋ ค๋ฉด ์ธ ๋จ๊ณ๊ฐ ํ์ํ๋ค.ํ์ ์คํฌ๋ฆฝํธ ์ ์ธ ํ์ผ d.ts์
velog.io
์ด ๊ฒ์๋ฌผ์ ๋ณด๊ณ , ref์ ์ฌ์ฉํ์ฌ audio ๊ฐ์ฒด๋ฅผ ๊ด๋ฆฌ๋ฅผ ํด์ฃผ์๋ค.
const myRef = useRef<HTMLAudioElement>(null);
const onClickVolume = () => {
// ์ฌ์ ์ค
if (isPlay) {
myRef.current?.pause();
setIsPlay(false);
} else {
// ์์
์ฌ์
myRef.current?.play();
setIsPlay(true);
}
};
return (
<>
<InvBGMBlock>
<div className="volume__box" onClick={onClickVolume}>
{isPlay && <VolumeUpIcon />}
{!isPlay && <VolumeOffIcon />}
<audio ref={myRef} src={music}></audio>
</div>
</InvBGMBlock>
...์๋ต
์ ๋๋ค! ๐๐