audio 사운드 하나를 연속하여 반복/중복 재생 하는 방법

yellowbutter·2024년 2월 1일
0

TIL

목록 보기
22/25
post-thumbnail

현재 개발 하는 게임에서 타이머 10 -> 1까지 카운트 다운으로 10, 9, 8, ...1 까지 소리를 호출하고 있다.

그런데 내가 받은 사운드가 1초보다 조금 긴 탓인지
10, 8, 6.. 번째만 소리가 났다.

이유

Audio객체는
play()가 호출되어 재생이 시작 되면, 끝까지 재생이 완료되기 전에는 반복 호출하여 재생할 수 없다.

해결책

미리 여러개의 Auido객체를 생성해두고, 배열에 담아두고 사용한다.

구현한 코드

타이머가 1초씩 줄어들음과 동시에
1~10초에는 countdown 소리를 낸다.

 
 const arr_sound = [];

  for (let i = 1; i <= 11; i++) {
    const sound = new Audio(countdownsound);
    arr_sound.push(sound);
  }

  const countDownSound = number => {
    arr_sound[number - 1].play();
  };


useEffect(() => {
    const intervalId = setInterval(() => {
      setTimer(prevTimer => {
        if (prevTimer > 0) {
          if (prevTimer >= 1 && prevTimer <= 11) {
            countDownSound();
          }
          return prevTimer - 1;
        } else {
          clearInterval(intervalId);
          return 0;
        }
      });
    }, 1000);
    return () => {
      clearInterval(intervalId);
    };
  }, [timer]);

참고자료
Javascript: Audio 사운드 하나를 연속하여 반복/중복 재생하는 방법
출처: https://curryyou.tistory.com/339 [카레유:티스토리]

profile
기록은 희미해지지 않는다 🐾🧑‍💻

0개의 댓글