使用react-native-audio录音

时间:2020-05-01

文档:https://www.npmjs.com/package/react-native-audio

下面的代码只针对安卓,ios需要参考文档进行部分修改!

安装react-native-audio

npm install react-native-audio --save
react-native link react-native-audio

找到安卓的权限配置文件AndroidManifest.xml

android\app\src\main\AndroidManifest.xml

添加麦克风权限

<uses-permission android:name="android.permission.RECORD_AUDIO" />

修改了权限后需要重新启动应用,不然没效果。

开始使用

在组件中定义一个触发语音的按钮或其它可点击的组件

<TouchableOpacity
	style={styles.warnBtn}
	onPress={this.toVoice}
>
	<Text style={styles.warnColor}>开始语音</Text>
</TouchableOpacity>

点击之后执行toVoice方法

这个方法里面有录音的相关代码

toVoice = () => {
        this.startVoice();
        Alert.alert(
            '正在语音',
            '聆听中...',
            [
                {
                    text: '取消', onPress: () => {
                        AudioRecorder.stopRecording();
                        this.setState({
                            isToSearch: false,
                        });
                    }, style: 'cancel',
                },
                {
                    text: '确定', onPress: () => {
                        AudioRecorder.stopRecording();
                        this.setState({
                            isToSearch: true,
                        });
                    },
                },
            ],
            {cancelable: false},
        );
    };

startVoice() 方法为配置录音相关的代码,比如请求权限等

startVoice = () => {
        AudioRecorder.requestAuthorization()
            .then(isAuthorised => {
                if (!isAuthorised) {
                    return alert('请打开麦克风权限');
                }
                const option = {
                    SampleRate: 16000.0, //采样率
                    Channels: 1, //通道
                    AudioQuality: 'Low', //音质
                    AudioEncoding: 'amr_nb', //音频编码
                };
                AudioRecorder.prepareRecordingAtPath(this.state.audioPath, option);
                AudioRecorder.onProgress = (data) => {
                    this.setState({currentTime: Math.floor(data.currentTime)});
                };
                // 语音完成
                AudioRecorder.onFinished = (data) => {
                    // 去搜索,录制时长小于60秒
                    if (this.state.isToSearch && this.state.currentTime < 60 && data && data['audioFileURL']) {
                        this.toSearch(data['audioFileURL']);
                    }
                };
                AudioRecorder.startRecording();
            });
    };

录音的代码很简单的,里面包含我自己的代码逻辑。

完整代码

import React, {Component} from 'react';
import {Alert, Image, Text, TouchableOpacity, View} from 'react-native';
import styles from '../Styles';
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import {getRandStr} from '../util';

export default class VoiceScreen extends Component {
    constructor(props) {
        super(props);
    }

    state = {
        // 语音时长
        currentTime: 0,
        // 是否识别
        isToSearch: false,
    };

    componentDidMount(): void {
        let title = '';
        switch (this.props.route.params.type) {
            case 1:
                title = '语音搜题';
                break;
        }
        // 修改标题栏文字
        this.props.navigation.setOptions({
            title,
        });
        let audioPath = AudioUtils.DocumentDirectoryPath + '/' + getRandStr() + '.amr';
        this.setState({
            audioPath,
        });
    }

    startVoice = () => {
        AudioRecorder.requestAuthorization()
            .then(isAuthorised => {
                if (!isAuthorised) {
                    return alert('请打开麦克风权限');
                }
                const option = {
                    SampleRate: 16000.0, //采样率
                    Channels: 1, //通道
                    AudioQuality: 'Low', //音质
                    AudioEncoding: 'amr_nb', //音频编码
                };
                AudioRecorder.prepareRecordingAtPath(this.state.audioPath, option);
                AudioRecorder.onProgress = (data) => {
                    this.setState({currentTime: Math.floor(data.currentTime)});
                };
                // 语音完成
                AudioRecorder.onFinished = (data) => {
                    // 去搜索,录制时长小于60秒
                    if (this.state.isToSearch && this.state.currentTime < 60 && data && data['audioFileURL']) {
                        this.toSearch(data['audioFileURL']);
                    }
                };
                AudioRecorder.startRecording();
            });
    };

    toVoice = () => {
        this.startVoice();
        Alert.alert(
            '正在语音',
            '聆听中...',
            [
                {
                    text: '取消', onPress: () => {
                        AudioRecorder.stopRecording();
                        this.setState({
                            isToSearch: false,
                        });
                    }, style: 'cancel',
                },
                {
                    text: '确定', onPress: () => {
                        AudioRecorder.stopRecording();
                        this.setState({
                            isToSearch: true,
                        });
                    },
                },
            ],
            {cancelable: false},
        );
    };
    /**
     * 最后搜索的请求方法
     * @param filePath 语音文件位置
     */
    toSearch = (filePath) => {
        console.log(filePath);
    };

    render(): React.ReactNode {
        return (<View style={[styles.flexCenter, styles.bgColor]}>
            <Image
                source={require('../resources/images/voice_1.png')}
                style={{width: 64, height: 64}}
                tintColor='#fff'
            />
            <View style={styles.mt30}>
                <TouchableOpacity
                    style={styles.warnBtn}
                    onPress={this.toVoice}
                >
                    <Text style={styles.warnColor}>开始语音</Text>
                </TouchableOpacity>
            </View>
        </View>);
    }
}

AudioRecorder 下的方法

  • requestAuthorization    请求授权
  • checkAuthorizationStatus    检查授权状态
  • prepareRecordingAtPath    录制路径
  • startRecording    开始录音
  • pauseRecording    暂停录音
  • resumeRecording    恢复录音
  • stopRecording    停止录音
  • onProgress    录音进展
  • onFinished    完成录音

prepareRecordingPath(path,options) 接收两个参数
 - path 路径       - option 参数

options 参数:

  • SampleRate: 44100.0, //采样率
  • Channels: 2, //通道
  • AudioQuality: 'High', //音质(Low, Medium, High)
  • AudioEncoding: 'aac', //音频编码(aac编码iOS和Android均支持)
  • OutputFormat: 'mpeg_4', //输出格式
  • MeteringEnabled: false, //是否计量
  • MeasurementMode: false, //测量模式
  • AudioEncodingBitRate: 32000, //音频编码比特率
  • IncludeBase64: true, //是否是base64格式
  • AudioSource: 0, //音频源

iOS支持的编码类型:lpcm, ima4, aac, MAC3, MAC6, ulaw, alaw, mp1, mp2, alac, amr

android支持的编码类型:aac, aac_eld, amr_nb, amr_wb, he_aac, vorbis

AudioUtils 下的属性

  • AudioUtils 文件存放路径
  • CachesDirectoryPath 缓存目录路径
  • DocumentDirectoryPath 文档目录路径
  • LibraryDirectoryPath 图书馆目录路径
  • MainBundlePath 主路径

参考示例

import {AudioRecorder, AudioUtils} from 'react-native-audio';
let audioPath = AudioUtils.DocumentDirectoryPath + '/test.aac';

AudioRecorder.prepareRecordingAtPath(audioPath, {
  SampleRate: 22050,
  Channels: 1,
  AudioQuality: "Low",
  AudioEncoding: "aac"
});