All Projects → dooboolab → React Native Audio Recorder Player

dooboolab / React Native Audio Recorder Player

Licence: mit
react-native native module for audio recorder and player.

Programming Languages

java
68154 projects - #9 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to React Native Audio Recorder Player

1keys
A 1 Kilobyte JavaScript Piano
Stars: ✭ 118 (-52.42%)
Mutual labels:  audio-player
Swiftaudio
Audio player for iOS
Stars: ✭ 160 (-35.48%)
Mutual labels:  audio-player
Jcplayer
🎵 A simple audio player for Android applications.
Stars: ✭ 209 (-15.73%)
Mutual labels:  audio-player
React Jplayer
Html5 audio and video player library for React
Stars: ✭ 128 (-48.39%)
Mutual labels:  audio-player
Web
Angular6 music player to search and play YouTube, SoundCloud and Mixcloud tracks
Stars: ✭ 156 (-37.1%)
Mutual labels:  audio-player
Audiomotion.js
High-resolution real-time spectrum analyzer and music player using Web Audio and Canvas APIs.
Stars: ✭ 177 (-28.63%)
Mutual labels:  audio-player
Nymphcast
Audio and video casting system with support for custom applications.
Stars: ✭ 2,010 (+710.48%)
Mutual labels:  audio-player
Swift Radio Pro
Professional Radio Station App for iOS!
Stars: ✭ 2,644 (+966.13%)
Mutual labels:  audio-player
Html Midi Player
🎹 Play and display MIDI files on the web
Stars: ✭ 158 (-36.29%)
Mutual labels:  audio-player
Lmmediaplayer
A video and audio player with replaceable UI component.
Stars: ✭ 183 (-26.21%)
Mutual labels:  audio-player
React Native Sound Player
Play sound file in ReactNative
Stars: ✭ 144 (-41.94%)
Mutual labels:  audio-player
Cog
Cog - A Free and Open Source Audio Player for macOS 10.13+
Stars: ✭ 152 (-38.71%)
Mutual labels:  audio-player
Android Audiorecorder App
Android application to record audio. RxJava2, Dagger2, MVP, RoomDb.
Stars: ✭ 180 (-27.42%)
Mutual labels:  audio-player
Amplipi
Whole House Audio System 🔊
Stars: ✭ 125 (-49.6%)
Mutual labels:  audio-player
Musikcube
a cross-platform, terminal-based music player, audio engine, metadata indexer, and server in c++
Stars: ✭ 2,663 (+973.79%)
Mutual labels:  audio-player
Sbplayerclient
支持全格式的mac版视频播放器
Stars: ✭ 110 (-55.65%)
Mutual labels:  audio-player
Muzonchik
iOS Music App that let you search, download and play music
Stars: ✭ 170 (-31.45%)
Mutual labels:  audio-player
React Audio Component
A beautiful example project demonstrating how to build an audio player in React.
Stars: ✭ 239 (-3.63%)
Mutual labels:  audio-player
React H5 Audio Player
React audio player component with UI. It provides time indicator on both desktop and mobile devices.
Stars: ✭ 226 (-8.87%)
Mutual labels:  audio-player
Fradioplayer
A simple radio player framework for iOS, macOS, tvOS.
Stars: ✭ 183 (-26.21%)
Mutual labels:  audio-player

react-native-audio-recorder-player

Npm Version Downloads Build Status Greenkeeper badge 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.

Free read

Breaking Changes

  • 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.

Preview

Migration Guide

1.. 2..
startRecord startRecorder
stopRecord stopRecorder
startPlay startPlayer
stopPlay stopPlayer
pausePlay pausePlayer
resume resumePlayer
seekTo seekToPlayer
setSubscriptionDuration
setRecordInterval addRecordBackListener
removeRecordInterval ``
setVolume

Getting started

$ npm install react-native-audio-recorder-player --save

Mostly automatic installation

Using React Native >= 0.60

Linking the package manually is not required anymore with Autolinking.

  • iOS Platform:

    $ cd ios && pod install && cd .. # CocoaPods on iOS needs this extra step

  • Android Platform with Android Support:

    Using Jetifier tool for backward-compatibility.

    Modify your android/build.gradle configuration:

    buildscript {
      ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        # Only using Android Support libraries
        supportLibVersion = "28.0.0"
      }
    
  • Android Platform with AndroidX:

    Modify your android/build.gradle configuration:

    buildscript {
      ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        # Remove 'supportLibVersion' property and put specific versions for AndroidX libraries
        androidXAnnotation = "1.1.0"
        androidXBrowser = "1.0.0"
        // Put here other AndroidX dependencies
      }
    

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 LibrariesAdd Files to [your project's name]
  2. Go to node_modulesreact-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 PhasesLink Binary With Libraries
  4. Run your project (Cmd+R)<

Android

  1. Open up android/app/src/main/java/[...]/MainApplication.java
  • Add import com.dooboolab.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

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

<key>NSMicrophoneUsageDescription</key>
<string>This sample uses the microphone to record your speech and convert it to text.</string>

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" />

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 started the recording.

if (Platform.OS === 'android') {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      {
        title: 'Permissions for write access',
        message: 'Give permission to your storage to write a file',
        buttonPositive: 'ok',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('You can use the storage');
    } else {
      console.log('permission denied');
      return;
    }
  } catch (err) {
    console.warn(err);
    return;
  }
}
if (Platform.OS === 'android') {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
      {
        title: 'Permissions for write access',
        message: 'Give permission to your storage to write a file',
        buttonPositive: 'ok',
      },
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log('You can use the camera');
    } else {
      console.log('permission denied');
      return;
    }
  } catch (err) {
    console.warn(err);
    return;
  }
}

Methods

All methods are implemented with promises.

Func Param Return Description
mmss number seconds string Convert seconds to minute:second string.
addRecordBackListener Function callBack void Get callback from native module. Will receive current_position, current_metering (if configured in startRecorder)
addPlayBackListener Function callBack void Get callback from native module. Will receive duration, current_position
startRecorder <string> uri? <boolean> meteringEnabled? Promise<void> Start recording. Not passing uri will save audio in default location.
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 doulbe value Promise<string> Set volume of audio player (default 1.0, range: 0.0 ~ 1.0).

Customizing recorded audio quality (from 2.3.0)

interface AudioSet {
  AVSampleRateKeyIOS?: number;
  AVFormatIDKeyIOS?: AVEncodingType;
  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,
      AVEncoderAudioQualityKeyIOS: AVEncoderAudioQualityIOSType.high,
      AVNumberOfChannelsKeyIOS: 2,
      AVFormatIDKeyIOS: AVEncodingOption.aac,
    };
    const meteringEnabled = false; 

    const uri = await this.audioRecorderPlayer.startRecorder(path, meteringEnabled, audioSet);
    
    this.audioRecorderPlayer.addRecordBackListener((e: any) => {
      this.setState({
        recordSecs: e.current_position,
        recordTime: this.audioRecorderPlayer.mmssss(
          Math.floor(e.current_position),
        ),
      });
    });

Default Path

  • Default path for android uri is sdcard/sound.mp4.
  • Default path for ios uri is 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.current_position,
      recordTime: this.audioRecorderPlayer.mmssss(
        Math.floor(e.current_position),
      ),
    });
    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.current_position,
      currentDurationSec: e.duration,
      playTime: this.audioRecorderPlayer.mmssss(Math.floor(e.current_position)),
      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.

const path = Platform.select({
  ios: 'hello.m4a',
  android: 'sdcard/hello.mp4', // should give extra dir name in android. Won't grant permission to the first level of dir.
});
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 npm install && npm start.
  3. Run npm run ios to run on ios simulator and npm run android to run on your android device.

TODO

  • [ ] Better android permission handling
  • [x] Volume Control
  • [x] Sync timing for recorder callback handler

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].