📱Mobile/React Native

[React Native] react-native-sound를 사용해서 진동모드일 때 오디오 재생하기

뉴발자 2025. 9. 7.
반응형

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

개요

사이드 프로젝트를 진행하는 중 오디오 재생 시 이어폰을 꼈을 때는 음성이 잘 나왔지만 기기 자체에서는 음성이 나오지 않았다.

 

 

해결 방법

react-native-sound 라이브러리 객체의 setCategory 설정을 'Playback'으로 설정해주니 정상적으로 음성이 재생됐다.

반응형

 

 

코드

// tts.ts
import Sound from "react-native-sound";

export const onPlayAudio = (filePath: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    // 이전 재생 중인 오디오가 있다면 정지 및 해제
    if (currentSound) {
      currentSound.stop();
      currentSound.release();
      currentSound = null;
    }

    // 진동 모드에서도 소리가 나도록 설정
    Sound.setCategory("Playback");

    // 새로운 사운드 생성
    currentSound = new Sound(filePath, "", (error) => {
      if (error) {
        console.error("오디오 로드 중 오류 발생: ", error);
        currentSound = null;
        reject(error);
        return;
      }

      // 오디오 재생
      currentSound?.play(success => {
        if (success) {
          console.log("오디오 재생 완료");
          if (currentSound) {
            currentSound.release();
            currentSound = null;
          }
          resolve();
        } else {
          console.error("오디오 재생 실패");
          if (currentSound) {
            currentSound.release();
            currentSound = null;
          }
          reject(new Error("오디오 재생 실패"));
        }
      });
    });
  });
};

 

 

 

 

 

 

 

 

 

 

반응형

댓글