I am learning React Native and I am working in an app. I spent some days now trying to find a way to do this:
I have a simple app with buttons. I need to record audio and send it to an API every 5 seconds. (in the code you will see 6 seconds)
I need to give the user the hability to stop the sending of audio, I thought that this could be accomplished by pressing buttons to change a state that would stop the communication with the API.
Here is my reasoning.
export default function App() {
const [recording, setRecording] = React.useState();
...
const uploadAudio = async (path) => {
const formData = new FormData()
...
async function startStreamRec () {
if (stream) {
try {
const repet= setInterval(async ()=> {
await Audio.requestPermissionsAsync();
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
});
const recording = new Audio.Recording();
await recording.prepareToRecordAsync(Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY);
await recording.startAsync();
setRecording(recording);
console.log('Recording started');
console.log(disable);
console.log('Stopping recording..');
setRecording(undefined);
recording.stopAndUnloadAsync();
const uri = recording.getURI();
console.log('Recording stopped and stored at', uri);
setPath(uri);
uploadAudio(uri);
}, 6000);
} catch (err) {
console.error('Failed to start recording', err);
}
} else {
clearInterval(repet);
}
}
async function stopStream() {
setStream(false);
startStreamRec();
}
async function startStream() {
setStream(true);
startStreamRec();
}
return (
<View>
...
<TouchableOpacity onPress={startStream} style={styles.cathButton}>
<Text> Start</Text>
</TouchableOpacity>
<TouchableOpacity onPress={ stopStream } style={styles.cathButton}>
<Text> Stop </Text>
</TouchableOpacity>
...
</View>
);
}
However, this code doenst is not working properly.
I have tryied some things with useeffect, with state hooks, while cycles of settimeout, setState but everything failed. A common error I'm getting is " error: too many re-renders. react limits the number of renders to prevent an infinite loop."
I don't know what I'm doing wrong.