• Stars
    star
    554
  • Rank 80,342 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

react-native native module for audio recorder and player.

react-native-audio-recorder-player

yarn Version Downloads CI publish-package License supports iOS supports Android code style: prettier LICENSE

This is a react-native link module for audio recorder and player. This is not a playlist audio module and this library provides simple recorder and player functionalities for both android and ios platforms. This only supports default file extension for each platform. This module can also handle file from url.

Preview

Free read

Breaking Changes

  • From version 3.0.+, a critical migration has been done. Current version is not much different from version 2.0.+ in usability, but there are many changes internally. Also note that it supports iOS platform version 10.0 or newer.

    1. Codebase has been re-written to kotlin for Android and swift for iOS. Please follow the post installation for this changes.

      [iOS]

    2. pauseRecorder and resumeRecorder features are added.

      • Caveat Android now requires minSdk of 24.
    3. Renamed callback variables.

      export type RecordBackType = {
        isRecording?: boolean;
        currentPosition: number;
        currentMetering?: number;
      };
      
      export type PlayBackType = {
        isMuted?: boolean;
        currentPosition: number;
        duration: number;
      };
    4. subscriptionDuration offset not defaults to 0.5 which is 500ms.

  • There has been vast improvements in #114 which is released in 2.3.0. We now support all RN versions without any version differenciating. See below installation guide for your understanding.

Migration Guide

1.x.x 2.x.x & 3.x.x
startRecord startRecorder
pauseRecorder (3.x.x)
resumeRecorder (3.x.x)
stopRecord stopRecorder
startPlay startPlayer
stopPlay stopPlayer
pausePlay pausePlayer
resume resumePlayer
seekTo seekToPlayer
setSubscriptionDuration
addPlayBackListener addPlayBackListener
setRecordInterval addRecordBackListener
removeRecordInterval ``
setVolume

Getting started

$ yarn add react-native-audio-recorder-player

Installation

Using React Native >= 0.61

[iOS only]

npx pod-install

Using React Native < 0.60

$ react-native link react-native-audio-recorder-player

Manual installation

iOS

  1. In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]
  2. Go to node_modules ➜ react-native-audio-recorder-player and add RNAudioRecorderPlayer.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libRNAudioRecorderPlayer.a to your project's Build Phases ➜ Link Binary With Libraries
  4. Run your project (Cmd+R)<

Android

  1. Open up android/app/src/main/java/[...]/MainApplication.java
  • Add import package com.dooboolab.audiorecorderplayer.RNAudioRecorderPlayerPackage; to the imports at the top of the file
  • Add new RNAudioRecorderPlayerPackage() to the list returned by the getPackages() method
  1. Append the following lines to android/settings.gradle:
    include ':react-native-audio-recorder-player'
    project(':react-native-audio-recorder-player').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-audio-recorder-player/android')
    
  2. Insert the following lines inside the dependencies block in android/app/build.gradle:
      compile project(':react-native-audio-recorder-player')
    

Post installation

iOS

On iOS you need to add a usage description to Info.plist:

<key>NSMicrophoneUsageDescription</key>
<string>Give $(PRODUCT_NAME) permission to use your microphone. Your record wont be shared without your permission.</string>

Also, add swift bridging header if you haven't created one for swift compatibility.

1

Android

On Android you need to add a permission to AndroidManifest.xml:

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

Also, android above Marshmallow needs runtime permission to record audio. Using react-native-permissions will help you out with this problem. Below is sample usage before when before staring the recording.

if (Platform.OS === 'android') {
  try {
    const grants = await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
    ]);

    console.log('write external stroage', grants);

    if (
      grants['android.permission.WRITE_EXTERNAL_STORAGE'] ===
        PermissionsAndroid.RESULTS.GRANTED &&
      grants['android.permission.READ_EXTERNAL_STORAGE'] ===
        PermissionsAndroid.RESULTS.GRANTED &&
      grants['android.permission.RECORD_AUDIO'] ===
        PermissionsAndroid.RESULTS.GRANTED
    ) {
      console.log('Permissions granted');
    } else {
      console.log('All required permissions not granted');
      return;
    }
  } catch (err) {
    console.warn(err);
    return;
  }
}

Lastly, you need to enable kotlin. Please change add the line below in android/build.gradle.

buildscript {
  ext {
      buildToolsVersion = "29.0.3"
+     // Note: Below change is necessary for pause / resume audio feature. Not for Kotlin.
+     minSdkVersion = 24
      compileSdkVersion = 29
      targetSdkVersion = 29
+     kotlinVersion = '1.6.10'

      ndkVersion = "20.1.5948944"
  }
  repositories {
      google()
      jcenter()
  }
  dependencies {
      classpath("com.android.tools.build:gradle:4.2.2")
+     classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
  }
...

Methods

All methods are implemented with promises.

Func Param Return Description
mmss number seconds string Convert seconds to minute:second string
setSubscriptionDuration void Set default callback time when starting recorder or player. Default to 0.5 which is 500ms
addRecordBackListener Function callBack void Get callback from native module. Will receive currentPosition, currentMetering (if configured in startRecorder)
removeRecordBackListener Function callBack void Removes recordback listener
addPlayBackListener Function callBack void Get callback from native module. Will receive duration, currentPosition
removePlayBackListener Function callBack void Removes playback listener
startRecorder <string> uri? <boolean> meteringEnabled? Promise<void> Start recording. Not passing uri will save audio in default location.
pauseRecorder Promise<string> Pause recording.
resumeRecorder Promise<string> Resume recording.
stopRecorder Promise<string> Stop recording.
startPlayer string uri? Record<string, string> httpHeaders? Promise<string> Start playing. Not passing the param will play audio in default location.
stopPlayer Promise<string> Stop playing.
pausePlayer Promise<string> Pause playing.
seekToPlayer number miliseconds Promise<string> Seek audio.
setVolume double value Promise<string> Set volume of audio player (default 1.0, range: 0.0 ~ 1.0).

Able to customize recorded audio quality (from 2.3.0)

interface AudioSet {
  AVSampleRateKeyIOS?: number;
  AVFormatIDKeyIOS?: AVEncodingType;
  AVModeIOS?: AVModeType;
  AVNumberOfChannelsKeyIOS?: number;
  AVEncoderAudioQualityKeyIOS?: AVEncoderAudioQualityIOSType;
  AudioSourceAndroid?: AudioSourceAndroidType;
  OutputFormatAndroid?: OutputFormatAndroidType;
  AudioEncoderAndroid?: AudioEncoderAndroidType;
}

More description on each parameter types are described in index.d.ts. Below is an example code.

const audioSet: AudioSet = {
  AudioEncoderAndroid: AudioEncoderAndroidType.AAC,
  AudioSourceAndroid: AudioSourceAndroidType.MIC,
  AVModeIOS: AVModeIOSOption.measurement,
  AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
  AVNumberOfChannelsKeyIOS: 2,
  AVFormatIDKeyIOS: AVEncodingOption.aac,
};
const meteringEnabled = false;

const uri = await this.audioRecorderPlayer.startRecorder(
  path,
  audioSet,
  meteringEnabled,
);

this.audioRecorderPlayer.addRecordBackListener((e: any) => {
  this.setState({
    recordSecs: e.currentPosition,
    recordTime: this.audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
  });
});

Default Path

  • Default path for android uri is {cacheDir}/sound.mp4.
  • Default path for ios uri is {cacheDir}/sound.m4a.

Usage

import AudioRecorderPlayer from 'react-native-audio-recorder-player';

const audioRecorderPlayer = new AudioRecorderPlayer();

onStartRecord = async () => {
  const result = await this.audioRecorderPlayer.startRecorder();
  this.audioRecorderPlayer.addRecordBackListener((e) => {
    this.setState({
      recordSecs: e.currentPosition,
      recordTime: this.audioRecorderPlayer.mmssss(
        Math.floor(e.currentPosition),
      ),
    });
    return;
  });
  console.log(result);
};

onStopRecord = async () => {
  const result = await this.audioRecorderPlayer.stopRecorder();
  this.audioRecorderPlayer.removeRecordBackListener();
  this.setState({
    recordSecs: 0,
  });
  console.log(result);
};

onStartPlay = async () => {
  console.log('onStartPlay');
  const msg = await this.audioRecorderPlayer.startPlayer();
  console.log(msg);
  this.audioRecorderPlayer.addPlayBackListener((e) => {
    this.setState({
      currentPositionSec: e.currentPosition,
      currentDurationSec: e.duration,
      playTime: this.audioRecorderPlayer.mmssss(Math.floor(e.currentPosition)),
      duration: this.audioRecorderPlayer.mmssss(Math.floor(e.duration)),
    });
    return;
  });
};

onPausePlay = async () => {
  await this.audioRecorderPlayer.pausePlayer();
};

onStopPlay = async () => {
  console.log('onStopPlay');
  this.audioRecorderPlayer.stopPlayer();
  this.audioRecorderPlayer.removePlayBackListener();
};

TIPS

If you want to get actual uri from the record or play file to actually grab it and upload it to your bucket, just grab the resolved message when using startPlay or startRecord method like below.

To access the file with more reliability, please use rn-fetch-blob. For example, below.

const dirs = RNFetchBlob.fs.dirs;
const path = Platform.select({
  ios: 'hello.m4a',
  android: `${this.dirs.CacheDir}/hello.mp3`,
});

const uri = await audioRecorderPlayer.startRecord(path);

Also, above example helps you to setup manual path to record audio. Not giving path param will record in default path as mentioned above.

Try yourself

  1. Goto Example folder by running cd Example.
  2. Run yarn install && yarn start.
  3. Run yarn ios to run on ios simulator and yarn android to run on your android device.

Special Thanks

mansya - logo designer.

Help Maintenance

I've been maintaining quite many repos these days and burning out slowly. If you could help me cheer up, buying me a cup of coffee will make my life really happy and get much energy out of it.
Buy Me A Coffee Paypal

More Repositories

1

react-native-masonry-list

The Masonry List implementation which has similar implementation as the `FlatList` in React Native
TypeScript
308
star
2

dooboo-ui-legacy

React Native UI Components with react-hook (web, ios, android)
TypeScript
143
star
3

dooboo-native-ts

Complete boilerplate for react-native app. Contains, typescript, react-hook, context-api, ts-jest, localization, navigation and etc.
TypeScript
81
star
4

react-native-drop-down-item

Dropdown list item for react-native.
JavaScript
51
star
5

DoobooIAP

Aims for feature set examples of react-native-iap
TypeScript
45
star
6

react-native-training

React Native Tutorials
JavaScript
40
star
7

reanimated-masonry-list

Masonry List with Reanimated2 component
TypeScript
40
star
8

react-navigation-sample

Examples for react-navigation v5 apis
TypeScript
34
star
9

BooKooX

The social ledger app
Dart
34
star
10

talktalk-rn

(Deprecated via hackatalk-mobile) talktalk app built in react-native.
TypeScript
30
star
11

hackatalk-server

HackaTalk backend server
TypeScript
23
star
12

Hygiene

Universal app (ios, android, web) built in expo. Individual contribution to Covid-19 Pandemic.
TypeScript
21
star
13

ts-apollo-sequelize

Graphql apollo typescript example
TypeScript
19
star
14

expo-relay-boilerplate

Relay hooks integration with expo-web
TypeScript
18
star
15

talktalk-node

(Deprecated via hackatalk-server) Graphql node project using prisma for talktalk.
TypeScript
16
star
16

style-guide

The coding guildlines for React and React Native
15
star
17

github-stats

Github readme stats in multi angles.
TypeScript
10
star
18

talktalk-flutter

Chat App with Flutter.
Dart
9
star
19

TodoMagic

Simple todo app built in SwiftUI and Jetpack Compose
Swift
9
star
20

react-native-typescript-starter

Starter project for react native and typescript.
TypeScript
8
star
21

flat_list

Flutter's [FlatList] widget for React Native friendly developers
Dart
8
star
22

relay-expo-workshop

Relay integration with expo and typescript and all its usage
TypeScript
7
star
23

WeHack

Opensource Hackathon in 2021!
Dart
7
star
24

react-navigation-v3-example

React Navigation v3 example.
JavaScript
6
star
25

starter-rn

RNProject
JavaScript
6
star
26

react-native-shorts-example

Youtube shorts example with react-native
Java
6
star
27

hyochan

5
star
28

react-redux-ts-styled-boilerplate

react web boilerplate with redux and typescript.
TypeScript
5
star
29

react-typescript-vite

React boilerplate with typescript and vite
TypeScript
4
star
30

dooboo.dev

Community tools for dooboolab
TypeScript
4
star
31

react-native-fbt

React Native FBT
Java
4
star
32

starter-expo

starter for expo project which is smiliar to starter-rn
JavaScript
3
star
33

expo-router-boilerplate

Expo typescript starter with expo router
TypeScript
3
star
34

hackatalk-website

HackaTalk website
TypeScript
3
star
35

legacy.dooboolab.com

dooboolab.com react responsive webpage.
TypeScript
3
star
36

flutter_navigation_sample

Flutter navigation sample in 2023
C++
2
star
37

hyochan.dev

Who am I
HTML
2
star
38

nvim

My nvim config
Vim Script
2
star
39

ts-node-koa-example

Typescript koa node example project.
TypeScript
2
star
40

kakao_login_android

Android sample project for kakao login.
Java
2
star
41

project-express-angular1

My first angular1 project with express server. Generally implemented sns functionalities.
JavaScript
1
star
42

dooboo.org

Documentation for dooboo
TypeScript
1
star
43

youtube_iframe

HTML
1
star
44

react-native-mobx-example

Simple react-native-mobx-example project.
JavaScript
1
star
45

flutter_boilerplate

Flutter boilerplate for embedding V2
Dart
1
star