React-Native 录音, 播放音频

录音

官方配置未详细给出,
这里写下步骤:

1: 安装依赖:
npm install react-native-audio --save
自动安装: 可以试下, 如果不行在按步骤手动配置安装
react-native link react-native-audio
2: 手动安装:
  • 1: android/settings.gradle:
+ include ':react-native-audio'
+ project(':react-native-audio').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-audio/android')

  • 2: android/app/build.gradle:

     dependencies {
       ...
      compile "com.facebook.react:react-native:+"  // From node_modules
    +  compile project(':react-native-audio')
    }
    
  • 3: android/app/src/main/java/com/XXX(项目名称)/MainApplication.java:

         + import com.rnim.rn.audio.ReactNativeAudioPackage;
    
        public class MainApplication extends Application implements ReactApplication {
        //......
        @Override
        protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
        +   new ReactNativeAudioPackage(),
            new MainReactPackage()
        );
        }
    ......
    }
    
  • 4: android/app/src/main/AndroidManifest.xml

    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    
主要的方法, 由于都是异步 ,所以需要按照代码例子中使用 async await 函数

1: 录音: AudioRecorder.startRecording() 且返回文件路径,
2: 停止: AudioRecorder.stopRecording() 且返回文件路径,
3: 暂停: AudioRecorder.pauseRecording() 且返回文件路径,
4: 播放声音, 使用的是 react-native-sound

代码:

首先请确保按照步骤安装了依赖 react-native-audioreact-native-sound

import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableHighlight, Platform, PermissionsAndroid } from 'react-native';
import { Button, WingBlank, WhiteSpace } from 'antd-mobile';

import NavBar from './NavBar';
import Sound from 'react-native-sound';                        // 播放声音组件
import {AudioRecorder, AudioUtils} from 'react-native-audio';
// let audioPath = AudioUtils.DocumentDirectoryPath + '/test.aac';
// 目录/data/user/0/com.opms_rn/files/test.aac

class TestRecordAudio extends Component {
  constructor(props){
    super(props);
    this.state = {
      currentTime: 0.0,                                                   //开始录音到现在的持续时间
      recording: false,                                                   //是否正在录音
      stoppedRecording: false,                                            //是否停止了录音
      finished: false,                                                    //是否完成录音
      audioPath: AudioUtils.DocumentDirectoryPath + '/test.aac',          //路径下的文件名
      hasPermission: undefined,                                           //是否获取权限
    };

    this.prepareRecordingPath = this.prepareRecordingPath.bind(this);     //执行录音的方法
    this.checkPermission = this.checkPermission.bind(this);               //检测是否授权
    this.record = this.record.bind(this);                                 //录音
    this.stop = this.stop.bind(this);                                     //停止
    this.play = this.play.bind(this);                                     //播放
    this.pause = this.pause.bind(this);                                   //暂停
    this.finishRecording = this.finishRecording.bind(this);
  }

  prepareRecordingPath(audioPath){
    AudioRecorder.prepareRecordingAtPath(audioPath, {
      SampleRate: 22050,
      Channels: 1,
      AudioQuality: "Low",            //录音质量
      AudioEncoding: "aac",           //录音格式
      AudioEncodingBitRate: 32000     //比特率
    });
  }

  checkPermission() {
    if (Platform.OS !== 'android') {
      return Promise.resolve(true);
    }

    const rationale = {
      'title': '获取录音权限',
      'message': 'XXX正请求获取麦克风权限用于录音,是否准许'
    };

    return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, rationale)
      .then((result) => {
        // alert(result);     //结果: granted ,    PermissionsAndroid.RESULTS.GRANTED 也等于 granted
        return (result === true || PermissionsAndroid.RESULTS.GRANTED)
      })
  }

  async record() {
    // 如果正在录音
    if (this.state.recording) {
      alert('正在录音中!');
      return;
    }

    //如果没有获取权限
    if (!this.state.hasPermission) {
      alert('没有获取录音权限!');
      return;
    }

    //如果暂停获取停止了录音
    if(this.state.stoppedRecording){
      this.prepareRecordingPath(this.state.audioPath);
    }

    this.setState({recording: true});

    try {
      const filePath = await AudioRecorder.startRecording();
    } catch (error) {
      console.error(error);
    }
  }

  async stop() {
    // 如果没有在录音
    if (!this.state.recording) {
      alert('没有录音, 无需停止!');
      return;
    }

    this.setState({stoppedRecording: true, recording: false});

    try {
      const filePath = await AudioRecorder.stopRecording();

      if (Platform.OS === 'android') {
        this.finishRecording(true, filePath);
      }
      return filePath;
    } catch (error) {
      console.error(error);
    }

  }

  async play() {
    // 如果在录音 , 执行停止按钮
    if (this.state.recording) {
      await this.stop();
    }

    // 使用 setTimeout 是因为, 为避免发生一些问题 react-native-sound中
    setTimeout(() => {
      var sound = new Sound(this.state.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);
  }

  async pause() {
    if (!this.state.recording) {
        alert('没有录音, 无需停止!');
        return;
      }

      this.setState({stoppedRecording: true, recording: false});

      try {
        const filePath = await AudioRecorder.pauseRecording();

        // 在安卓中, 暂停就等于停止
        if (Platform.OS === 'android') {
          this.finishRecording(true, filePath);
        }
      } catch (error) {
        console.error(error);
      }
  }

  finishRecording(didSucceed, filePath) {
      this.setState({ finished: didSucceed });
      console.log(`Finished recording of duration ${this.state.currentTime} seconds at path: ${filePath}`);
    }

  componentDidMount () {

    // 页面加载完成后获取权限
    this.checkPermission().then((hasPermission) => {
      this.setState({ hasPermission });

      //如果未授权, 则执行下面的代码
      if (!hasPermission) return;
      this.prepareRecordingPath(this.state.audioPath);

      AudioRecorder.onProgress = (data) => {
        this.setState({currentTime: Math.floor(data.currentTime)});
      };

      AudioRecorder.onFinished = (data) => {
        if (Platform.OS === 'ios') {
          this.finishRecording(data.status === "OK", data.audioFileURL);
        }
      };

    })
    // console.log(this.props.navigator)
    // console.log(audioPath)
  }

  render() {
    return (
      <View style={{flex:1}}>
        <NavBar
          title="录音"
          goBack={()=> this.props.navigator.pop()}
          />
          <WingBlank size="lg"style={{paddingTop: 20}}>
            <WhiteSpace size="md" />
            <Button type="primary" size="large" onClick={this.record}>录音</Button>
            <WhiteSpace size="md" />
            <Button type="primary" size="large" onClick={this.stop}>停止录音</Button>
            <WhiteSpace size="md" />
            <Button type="primary" size="large" onClick={this.pause}>暂停录音</Button>
            <WhiteSpace size="md" />
            <Button type="primary" size="large" onClick={this.play}>播放录音</Button>
          </WingBlank>
      </View>
    )
  }
}

export default TestRecordAudio;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容