reactnative实现录音功能

1.安装audio和sound模块:
react-native-audioreact-native-sound
2.在ANDROIDM.XML开启权限:

image.png

import * as React from 'react';
import {
ScrollView,
View,
StyleSheet,
TouchableHighlight,
Text,
Image,
} from 'react-native';
import Sound from 'react-native-sound';
import SelectorButton from '../components/SelectorButton';
import {AudioRecorder, AudioUtils} from 'react-native-audio';

export default function HomeScreen({navigation}) {
React.useEffect(() => {
AudioRecorder.requestAuthorization().then(isAuthorised => {
setHasPermission(isAuthorised);
prepareRecordingPath(audioPath);
AudioRecorder.onProgress = data => {
setCurrentTime(Math.floor(data.currentTime));
};
AudioRecorder.onFinished = data => {
// Android callback comes in the form of a promise instead.
if (Platform.OS === 'ios') {
_finishRecording(
data.status === 'OK',
data.audioFileURL,
data.audioFileSize,
);
}
};
});
}, []);

const [paused, setPaused] = React.useState(true);
const [currentTime, setCurrentTime] = React.useState(0);
const [recording, setRecording] = React.useState(false);
const [stoppedRecording, setStoppedRecording] = React.useState(false);
const [finished, setFinished] = React.useState(false);
const [hasPermission, setHasPermission] = React.useState(undefined);
const [audioPath, setAudioPath] = React.useState(
AudioUtils.DocumentDirectoryPath + '/test.aac',
);

const prepareRecordingPath = audioPath => {
AudioRecorder.prepareRecordingAtPath(audioPath, {
SampleRate: 22050,
Channels: 1,
AudioQuality: 'Low',
AudioEncoding: 'aac',
});
};

const _renderPauseButton = (onPress, active) => {
var style = active ? styles.activeButtonText : styles.buttonText;
var title = paused ? 'RESUME' : 'PAUSE';
return (

{title}

);
};

const _pause = async () => {
if (!recording) {
console.log("Can't pause, not recording!");
return;
}
try {
const filePath = await AudioRecorder.pauseRecording();
setPaused(true);
} catch (error) {
console.error(error);
}
};

const _resume = async () => {
if (!paused) {
console.log("Can't resume, not paused!");
return;
}
try {
await AudioRecorder.resumeRecording();
setPaused(false);
} catch (error) {
console.error(error);
}
};

const _play = async () => {
if (recording) {
await _stop();
}
setTimeout(() => {
var sound = new Sound(audioPath, '', error => {
if (error) {
console.log('failed to load the sound', error);
}
});
setTimeout(() => {
sound.play(success => {
if (success) {
console.log('successfully finished playing');
} else {
console.log('playback failed due to audio decoding errors');
}
});
}, 100);
}, 100);
};

const _stop = async () => {
if (!recording) {
console.log("Can't stop, not recording!");
return;
}
setStoppedRecording(true);
setRecording(false);
setPaused(true);
try {
const filePath = await AudioRecorder.stopRecording();
if (Platform.OS === 'android') {
_finishRecording(true, filePath);
}
return filePath;
} catch (error) {
console.error(error);
}
};

const _record = async () => {
if (recording) {
console.log('Already recording!');
return;
}
if (!hasPermission) {
console.log("Can't record, no permission granted!");
return;
}
if (stoppedRecording) {
prepareRecordingPath(audioPath);
}
setRecording(true);
setPaused(false);
try {
const filePath = await AudioRecorder.startRecording();
} catch (error) {
console.error(error);
}
};

const _renderButton = (title, onPress, active) => {
var style = active ? styles.activeButtonText : styles.buttonText;
return (

{title}

);
};

const _finishRecording = (didSucceed, filePath, fileSize) => {
setFinished(didSucceed);
console.log( Finished recording of duration ${currentTime} seconds at path: ${filePath} and size of ${ fileSize || 0 } bytes);
};

return (

style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'grey',
}}>
{_renderButton(
'RECORD',
() => {
_record();
},
recording,
)}
{_renderButton('PLAY', () => {
_play;
})}
{_renderButton('STOP', () => {
_stop();
})}
{_renderPauseButton(() => {
paused ? _resume() : _pause();
})}
{currentTime}s
{paused ? (
source={require('../assets/rank.png')}
style={{width: 50, height: 50}}>
) : (
source={require('../assets/icon_playing.gif')}
style={{width: 50, height: 50}}>
)}


);
}

const styles = StyleSheet.create({
activeButtonText: {
fontSize: 20,
color: '#B81F00',
},
buttonText: {
fontSize: 20,
color: '#fff',
},
progressText: {
paddingTop: 50,
fontSize: 50,
color: '#fff',
},
});

你可能感兴趣的:(reactnative实现录音功能)