skip to Main Content
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  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 } = await Audio.Recording.createAsync( Audio.RecordingOptionsPresets.HIGH_QUALITY
      );
      setRecording(recording);
      console.log('Recording started');
    } catch (err) {
      console.error('Failed to start recording', err);
    }
  }

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

  return (
    <View>
      <Button
        title={recording ? 'Stop Recording' : 'Start Recording'}
        onPress={recording ? stopRecording : startRecording}
      /> 
    </View>
  );
}

The code I have records audio when the button is pressed, and stops recording when the button is pressed again. How do I modify the code to stop the recording automatically once it has reached 15 seconds if the user hasn’t already pressed the button to stop it?

3

Answers


  1. Try with setTimeout:

    useEffect(() => {
      if (recording) {
        const timer = setTimeout(() => {
          stopRecording()
        }, 15000)
    
        return () => clearTimeout(timer);
      }
    }, [recording])
    
    Login or Signup to reply.
  2. It is possible to set a timeout of 15 seconds which calls the stopRecording function if it is still recording.

    setTimeout(() => {
      stopRecording();
    }, 15000);
    
    Login or Signup to reply.
  3. I think what you are looking for is the setTimeout function.

    The documentation can be found here:
    https://developer.mozilla.org/en-US/docs/Web/API/setTimeout

    For your use case, you would create a new function to handle a 15-second recording. It might look something like this:

    async function recordFor15Seconds() {
      startRecording();
      setTimeout(() => {
        stopRecording();
      }, 15000);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search