I'm building a voice recording application with Expo. This is my function to start voice recording, it works properly.
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 this is my 'stop' function, Recording stopped and stored...
async function stopRecording() {
console.log('Stopping recording..');
setRecording(undefined);
await recording.stopAndUnloadAsync();
const uri = recording.getURI();
console.log('Recording stopped and stored at', uri);
}
Now I want to play this saved sound with a play button. How can I reach this saved sound?
return (
<View style={styles.container}>
<Button
title={recording ? 'Stop Recording' : 'Start Recording'}
onPress={recording ? stopRecording : startRecording}
/>
</View>
);
I want to pass this stored uri as a file location. Is it possible in this way?
async function playSound() {
console.log('Loading Sound');
const { sound } = await Audio.Sound.createAsync(
require(RecordedURI)
);
setSound(sound);
console.log('Playing Sound');
await sound.playAsync();
}
This is the snack link: https://snack.expo.io/ZN9MBtpLd
First of all, you are assigning your state to
undefined
after you get the recording.I would suggest you to do something like this
Create two refs for
Recording
andPlaying
audio.And some states for
recordingStatus
,permission
etc.Snack for the recording implementation is here
Here's a GitHub Repo which has the implementation.
Screenshot of Result
I've added below the Rest of the implementation