[React-Native] 음성 녹음 및 재생

Gyuhan Park·2023년 3월 21일
3

react-native

목록 보기
2/7

아이폰 마이크 권한 얻기

$ npm install react-native-permissions

Podfile 맨 마지막 end 전에 아래 코드를 추가

  permissions_path = '../node_modules/react-native-permissions/ios'
  pod 'Permission-SpeechRecognition', :path => "#{permissions_path}/SpeechRecognition"

info.plist 에 아래 코드 추가

  <key>NSSpeechRecognitionUsageDescription</key>
  <string>YOUR TEXT</string>

pod install

$ cd ios
$ pod install

Usage

const checkRecordPermission = async () => {
    try {
      await request(PERMISSIONS.IOS.SPEECH_RECOGNITION).then((result) => {
        if (result === 'granted') {
          setMikePermission(true); // 권한에 따라 분기처리 해주기
        }
      });
    } catch (e) {
      console.log(`에러 \n ${e}`);
    }
  };

음성 녹음 및 재생

$ npm install react-native-audio-recorder-player

info.plist 에 아래 코드 추가

<key>NSMicrophoneUsageDescription</key>
<string>Give $(PRODUCT_NAME) permission to use your microphone. Your record wont be shared without your permission.</string>

pod install

cd ios
pod install

Usage

import AudioRecorderPlayer from 'react-native-audio-recorder-player';

const audioRecorderPlayer = new AudioRecorderPlayer();

const App = () => {
  const [recordDuration, setRecordDuration] = useState({
    recordSecs: 0,
    recordTime: '00:00:00',
  });
  const [playerDuration, setPlayerDuration] = useState({
    currentPositionSec: 0,
    currentDurationSec: 0,
    playTime: '00:00:00',
    duration: '00:00:00',
  });
  ...
  // 녹음 시작
  const handleStartRecord = async () => {
    if (audioRecorderPlayer) {
      setRecording(true);
      setPlayerDuration({
        ...playerDuration,
        currentPositionSec: 0,
        currentDurationSec: 0,
        playTime: '00:00:00',
        duration: '00:00:00',
      });
      await audioRecorderPlayer.startRecorder();
    }
    audioRecorderPlayer.addRecordBackListener((e) => {
      setRecordDuration({
        ...recordDuration,
        recordSecs: e.currentPosition,
        recordTime: audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
      });
    });
  };
  
  // 녹음 중지
  const handleStopRecord = async () => {
    if (audioRecorderPlayer) {
      setRecording(false);
      await audioRecorderPlayer.stopRecorder();
    }
    audioRecorderPlayer.removeRecordBackListener();
    setRecordDuration({ ...recordDuration, recordSecs: 0 });
  };
  
  // 음성 재생
  const soundStart = async () => {
    await audioRecorderPlayer.startPlayer();
    audioRecorderPlayer.addPlayBackListener((e) => {
      setPlayerDuration({
        currentPositionSec: e.currentPosition,
        currentDurationSec: e.duration,
        playTime: audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
        duration: audioRecorderPlayer.mmssss(Math.floor(e.duration)),
      });
    });
  };
}

결과 😎

RN 마이크 기능 사용하기
RN audio-recorder-player
RN permissions

profile
단단한 프론트엔드 개발자가 되고 싶은

0개의 댓글