Expo-av audio recording

Viewed 1446

I'm trying to record audio with expo-audio but it's showing an error when I start recording Error: Only one Recording object can be prepared at a given time. and Error: Cannot unload a Recording that has not been prepared. I also followed the documentation but still getting same error.

below is my code for starting recording

  const [recording, setRecording] = React.useState();

  async function startRecording() {
    try {
      console.log('Requesting permissions..');
      await Audio.requestPermissionsAsync();
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: true,
        playsInSilentModeIOS: true,
      }); 
      console.log('Starting recording..');
      const recording = new Audio.Recording();
      await recording.prepareToRecordAsync(Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY);
      await recording.startAsync(); 
      setRecording(recording);
      console.log('Recording started');
    } catch (err) {
      console.error('Failed to start recording', err);
    }
  }

and for stop recording

async function stopRecording() {
    console.log('Stopping recording..');
    setRecording(undefined);
    await recording.stopAndUnloadAsync();
    const uri = recording.getURI(); 
    console.log('Recording stopped and stored at', uri);
  }

anyone know why I'm getting that error?

1 Answers

Don't use recording as a state variable. Re-rendering makes the variable initialize again and again

Outside of the funtion or the class you are using declare a variable like this

let recording = new Audio.Recording();

Then use like this this

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Audio } from "expo-av";

let recording = new Audio.Recording();

export default function App() {
  async function startRecording() {
    try {
      console.log('Requesting permissions..');
      await Audio.requestPermissionsAsync();
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: true,
        playsInSilentModeIOS: true,
      });
      console.log('Starting recording..');
      await recording.prepareToRecordAsync(
        Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
      );
      await recording.startAsync();
      console.log('Recording started');
    } catch (err) {
      console.error('Failed to start recording', err);
    }
  }

  async function stopRecording() {
    console.log('Stopping recording..');
    await recording.stopAndUnloadAsync();
    const uri = recording.getURI();
    console.log('Recording stopped and stored at', uri);
  }

  return <View>// Your App contents here</View>;
}
Related