bgm 적용

순9·2024년 1월 31일

react고양이게임

목록 보기
5/14

StartPage컴포넌트에서
Howl를 사용 하여 게임시작 버튼을 눌렀을때
bgm재생되면서 게임시작

문제사항
bgm을 어디서 꺼야 하는지 게임을 처음으로 돌아가면
bgm이 겹치는 현상

문제 해결을 위해
App컴포넌트로 Howel연동 이동 useContext사용 전역상태관리로
다른 컴포넌트에서 받아 게임오버 된 뒤 음악 꺼짐

App

import { Howl } from 'howler';

//파이어베이스에서 가져오는 경로 
 const [audioURL, setAudioURL] = useState("");
//파이어베이스에서 bgm 데이터
 const [sound, setSound] = useState<Howl | null>(null);

//파이어베이스 경로
  const storage = getStorage(firebaseApp);
  const bgmRef = ref(storage, `bgm/in-search-of-the-rainbows-end-67.mp3`);
  
  
  //랜더링 될때
  useEffect(() => {
    const fetchAudioUrl = async () => {
      try {
      //데이터를 가져와서 setAudioURL로 데이터 보냄
        const url = await getDownloadURL(bgmRef);
        setAudioURL(url);
    } catch (error) {
        console.log(error);
      }
    };
    fetchAudioUrl();
  }, []);
  
 //audioURL 값이 변경 되면 랜더링을 함 
   useEffect(()=>{
   //데이터가 있으면 
    if(audioURL){
    //변수에 new Howl 값을 담음
        const newSound = new Howl({
            src:[audioURL], //데이터 경로
            html5:true,
        });
        //데이터 경로를 setSound에 보냄
        setSound(newSound); 
        newSound.play();
    }
},[audioURL]);

App return

  <gameBgmContext.Provider value={{sound}}>
      <Routes>
        <Route path="/" element= {<StartPage/>} />
        <Route path="/main" element={<MainPage />} />
        <Route path="/rank" element={<RankPage />} />
      </Routes>
  </gameBgmContext.Provider>
 

감싸진 컴포넌트들 한테value 값을 보냄

StartPage

const {sound} = useContext(gameBgmContext);

//함수 실행시에 bgm 재생
const handleStart = () => {
        if (sound) {
      sound.play();
    }
    navigation(`/main`);
  };

MainPage

const {sound} = useContext(gameBgmContext);
//함수 실행시 bgm 정지
const hadleRank = ()=>{
    if (sound) {
      sound.pause();
    }
   
    navigation(`/rank`);
  }
profile
1. 사용법 익히기 2. 원리가 뭔지 찾아보기 3. 원리를 공부하기

0개의 댓글