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?
>Solution :
Try with setTimeout:
useEffect(() => {
if (recording) {
const timer = setTimeout(() => {
stopRecording()
}, 15000)
return () => clearTimeout(timer);
}
}, [recording])