Coder Social home page Coder Social logo

hyochan / react-native-audio-recorder-player Goto Github PK

View Code? Open in Web Editor NEW
670.0 7.0 199.0 3.65 MB

react-native native module for audio recorder and player.

License: MIT License

JavaScript 1.42% TypeScript 25.03% Java 16.93% Objective-C 5.14% Ruby 2.44% Starlark 0.65% Kotlin 17.00% Swift 18.43% CMake 0.31% C++ 7.86% Objective-C++ 4.79%
react-native audio-player audio-recorder typescript java objective-c swift kotlin

react-native-audio-recorder-player's Introduction

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 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 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")
  }
...

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.

To pass in specific URI in IOS, you need to append file:// to the path. As an example using RFNS.

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

const uri = await audioRecorderPlayer.startRecord(path);

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

react-native-audio-recorder-player's People

Contributors

ahmedmohamedxyz avatar antonborovoi avatar aragorn171 avatar bang9 avatar breathingearth avatar ddowoo avatar dependabot[bot] avatar efstathiosntonas avatar escobar5 avatar greenkeeper[bot] avatar hufans avatar hyochan avatar lfoliveir4 avatar mansya avatar meeoh avatar mynameisguy avatar netbull avatar pavelpershkoaltoros avatar phecda avatar pipi32167 avatar pnthach95 avatar rajrohityadav avatar romainlq avatar rzulfikri avatar sanjaykmwt94222 avatar sargnec avatar sooryranga avatar udfalkso avatar vitorverasm avatar xammie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-audio-recorder-player's Issues

Error: setDataSource failed.

2.1.1

Platform Android

onStartPlay

console.log('onStartPlay');
const msg = await audioRecorderPlayer.startPlayer();
console.log(msg);
this.audioRecorderPlayer.addPlayBackListener((e) => {
if (e.current_position === e.duration) {
console.log('finished');
this.audioRecorderPlayer.stopPlayer();
}
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;
});

Steps to reprodue the behabior

onStartRecord and then onStartPlayer

the permissions are given

Error code:

Error: setDataSource failed.
Error: setDataSource failed.
at createErrorFromErrorData (blob:http://localhost:8081/484e680f-425f-48c2-be69-d8cbd47c9c8f:2007:17)
at blob:http://localhost:8081/484e680f-425f-48c2-be69-d8cbd47c9c8f:1959:27
at MessageQueue.__invokeCallback (blob:http://localhost:8081/484e680f-425f-48c2-be69-d8cbd47c9c8f:2510:18)
at blob:http://localhost:8081/484e680f-425f-48c2-be69-d8cbd47c9c8f:2257:18
at MessageQueue.__guard (blob:http://localhost:8081/484e680f-425f-48c2-be69-d8cbd47c9c8f:2414:13)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (blob:http://localhost:8081/484e680f-425f-48c2-be69-d8cbd47c9c8f:2256:14)
at http://localhost:8081/debugger-ui/debuggerWorker.js:72:58

Remove doobolab-welcome dependency.

I get it that is is nice to log out a welcome message. But it is a really dubious thing, especially for a package which would otherwise have zero dependencies.

Parameter path should be a path and not a file name on iOS

Version of react-native-audio-recorder-player

2.2.0

Platforms you faced the error (IOS or Android or both?)

iOS

Expected behavior

on method startRecorder, the parameter named path doesn't work as a path on iOS, it's just the fileName, it should be a path, on Android it works as a path.
This has some issues:

  • The functionality is inconsistent between both platforms
  • I can't save the iOS recording in a different location, just a different filename.

Actual behavior

The parameter passed to startRecorder is a fileName.

Make Compatible with androidx

Version of react-native-audio-recorder-player

2.1.4

Platforms you faced the error (IOS or Android or both?)

Android

Expected behavior

Builds without issue

Actual behavior

Build errors

Steps to reproduce the behavior

Just build and get errors:

Task :react-native-audio-recorder-player:compileDebugJavaWithJavac FAILED
/Users/jeremybradshaw/ccf-android/node_modules/react-native-audio-recorder-player/android/src/main/java/com/dooboolab/RNAudioRecorderPlayerModule.java:18: error: package android.support.annotation does not exist
import android.support.annotation.NonNull;
^
/Users/jeremybradshaw/ccf-android/node_modules/react-native-audio-recorder-player/android/src/main/java/com/dooboolab/RNAudioRecorderPlayerModule.java:19: error: cannot find symbol
import android.support.v4.app.ActivityCompat;
^
symbol: class ActivityCompat
location: package android.support.v4.app
/Users/jeremybradshaw/ccf-android/node_modules/react-native-audio-recorder-player/android/src/main/java/com/dooboolab/RNAudioRecorderPlayerModule.java:20: error: package android.support.v4.content does not exist
import android.support.v4.content.PermissionChecker;
^
/Users/jeremybradshaw/ccf-android/node_modules/react-native-audio-recorder-player/android/src/main/java/com/dooboolab/RNAudioRecorderPlayerModule.java:69: error: cannot find symbol
ActivityCompat.checkSelfPermission(reactContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED &&
^
symbol: variable ActivityCompat
location: class RNAudioRecorderPlayerModule
/Users/jeremybradshaw/ccf-android/node_modules/react-native-audio-recorder-player/android/src/main/java/com/dooboolab/RNAudioRecorderPlayerModule.java:70: error: cannot find symbol
ActivityCompat.checkSelfPermission(reactContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
^
symbol: variable ActivityCompat
location: class RNAudioRecorderPlayerModule
/Users/jeremybradshaw/ccf-android/node_modules/react-native-audio-recorder-player/android/src/main/java/com/dooboolab/RNAudioRecorderPlayerModule.java:73: error: cannot find symbol
ActivityCompat.requestPermissions(getCurrentActivity(), new String[]{
^
symbol: variable ActivityCompat
location: class RNAudioRecorderPlayerModule
6 errors

Background playing not working

Version of react-native-audio-recorder-player

2.0.8

Platforms you faced the error (IOS or Android or both?)

both

Expected behavior

Sound keeps playing in the background

Actual behavior

Sound stops if the app loses focus

Steps to reproduce the behavior

Run the example application, hit the play button, while playing hit the home button.

In the attached medium post, it says that the library supports background music playing, but when the app is in the background the sound stops, I looked in the code to see if there is some extra parameter I need to pass to addPlayBackListener but I cannot find anything.

I'm I missing something?

Error with Pause

when using the pause method the application hangs or gets very slow, the only option is to play and select stop, but the pause option is very necessary,

error uploading file

Version of react-native-audio-recorder-player

2.0.8

Platforms you faced the error (IOS or Android or both?)

both

const msg = await this.audioRecorderPlayer.startPlayer();

I am trying to send the variable msg using formData, when making the request it shows the following error

captura de pantalla 2018-11-16 a la s 4 48 47 p m

send audio by formdata

Version of react-native-audio-recorder-player

2.0.8

Platforms you faced the error (IOS or Android or both?)

both

when recording and playing an audio everything works fine, when I try to send it by formData, it's coming with a type of audio "audio/ x-m4a"

the way I'm sending it is (in iOS)

formData.append("incident[incident_description_attributes[file_name]]", {
uri: this.state.resultAudio,
name: 'test.m4a',
type: 'audio/m4a',
})

resultAudio is: const result = await this.audioRecorderPlayer.stopRecorder();

but when I receive the audio, it arrives in the following way

"file": {
"url": "....",
"name": "test.m4a",
"content_type": "audio/x-m4a",
"upload_date": "Dec 5, 2018",
"size": "3 MB"
}

uri is ok, but the file does not play

Pause function for recorder

Version of react-native-audio-recorder-player

Platforms you faced the error (IOS or Android or both?)

Expected behavior

should allow to pause / resume recorder

Actual behavior

Steps to reprodue the behabior

undefined is not an object (evaluating 'this.audioRecorderPlayer.startRecorder')

Version of react-native-audio-recorder-player

"react-native-audio-recorder-player": "^2.0.8",
"react-native": "^0.56.1",

Platforms you faced the error (IOS or Android or both?)

  • Android

I have imported the library and used the methods for the recording but getting the following type of error while start recording.

undefined is not an object (evaluating 'this.audioRecorderPlayer.startRecorder')

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

I cannot upload recorded audio to server

Currently I am on android platform But I am facing problem uploading the recorded audio using form data. This is how I am constructing the form data object at the moment.

I expect whenever I add the audio to form data it will be uploaded to server

I am getting the following error

error message TypeError: Network request failed
 at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
 at XMLHttpRequest.dispatchEvent (event-target.js:172)
 at XMLHttpRequest.setReadyState (XMLHttpRequest.js:578)
 at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:392)
 at XMLHttpRequest.js:505
 at RCTDeviceEventEmitter.emit (EventEmitter.js:190)
 at MessageQueue.__callFunction (MessageQueue.js:349)
 at MessageQueue.js:106
 at MessageQueue.__guard (MessageQueue.js:297)
 at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)

This is how I am currently uploading the audio to the server

const data = new FormData();
data.append("file", {
    name: "voice-note.mp4",
    type: 'audio/mpeg',
    uri: this.audioRecorderPlayer.startRecorder(path)
});
return fetch(base_url + end_point, {
    method: 'POST',
    headers: {
        'content-type': 'multipart/form-data',
        'x-guest-session-token': token
    },
    body: data
})
    .then(res => res.json())
    .then(response => {
        console.log(response);
        return response;
    })
    .catch(error => {
        console.log('error message', error);
    });

Audio input animation?

Is it possible to get some sort of stream or indication of input volume while recording to be able to generate an animation similar to the one below? Often it is helpful for the user to be able to see the animation correlate to their voice to know that everything is working as it should. Thanks!

Screen Shot 2019-06-08 at 10 57 28 PM

Help Needed.

Hello,
Thanks for such a stable and useful plugin.
I need to have a callback when an audio from network gets loaded and is ready to be played.
Please suggest how it can be done.

error: cannot find symbol class PermissionListener

Version of react-native-audio-recorder-player

latest

Platforms you faced the error (IOS or Android or both?)

android

Expected behavior

Actual behavior

android build error

Steps to reprodue the behabior

image

mediaPlayer is null

Version of react-native-audio-recorder-player

^2.1.1

Platforms you faced the error (IOS or Android or both?)

Android

Expected behavior

define one constant of player like this ::
const audioRecorderPlayer = new AudioRecorderPlayer();`

now recording success with this method ::
startRecord = async () => {
if (!await this.checkPermission()) {
console.log('permission problem')
return;
}
var RNFS = require('react-native-fs');
let dst = RNFS.DocumentDirectoryPath + '/files';
const path = Platform.select({
ios: dst + '/hello.m4a',
android: dst + '/hello.mp4', // should give extra dir name in android. Won't grant permission to the first level of dir.
});
const uri = await audioRecorderPlayer.startRecorder(path);
this.props.startRecording(uri);
audioRecorderPlayer.addRecordBackListener((e) => {
this.props.updateRecordingProgress(audioRecorderPlayer.mmssss(Math.floor(e.current_position)));
return;
});
console.log(uri);
};

after finishing recording stop like this :::
stopRecord = async () => {
this.props.stopRecording();
const result = await audioRecorderPlayer.stopRecorder();
audioRecorderPlayer.removeRecordBackListener();
console.log(result);

    console.log('wanna upload :: ' + this.props.record.uri)
    const uploadResult = await UploadFile(this.props.record.uri);
    console.log('audio uploadResult => ' + JSON.stringify(uploadResult))

    console.log('finish recording in :: ' + this.props.record.uri);
}

now i wanna play it with this command ::
plusClick = async () => {
console.log('plusClick')
var RNFS = require('react-native-fs');
let dst = RNFS.DocumentDirectoryPath + '/files';
const path = Platform.select({
ios: dst + '/hello.m4a',
android: dst + '/hello.mp4',
});
console.log('startPlayer :: ' + path)
const msg = await audioRecorderPlayer.startPlayer(path);
//audioRecorderPlayer.setVolume(1.0);
console.log(msg);
audioRecorderPlayer.addPlayBackListener((e) => {
if (e.current_position === e.duration) {
console.log('finished and called Stop');

            audioRecorderPlayer.stopPlayer().then(() => {

            });
        }
        this.setState({
            currentPositionSec: e.current_position,
            currentDurationSec: e.duration,
            playTime: audioRecorderPlayer.mmssss(Math.floor(e.current_position)),
            duration: audioRecorderPlayer.mmssss(Math.floor(e.duration)),
        });
        return;
    });
}

first time everythings is ok but second time error shows that ::
12-11 18:00:37.863 25690 30527 W ReactNativeJS: Error: mediaPlayer is null. 12-11 18:00:37.863 25690 30527 W ReactNativeJS: createErrorFromErrorData@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:7705:26 12-11 18:00:37.863 25690 30527 W ReactNativeJS: http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:7657:51 12-11 18:00:37.863 25690 30527 W ReactNativeJS: __invokeCallback@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:8187:23 12-11 18:00:37.863 25690 30527 W ReactNativeJS: http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:7934:34 12-11 18:00:37.863 25690 30527 W ReactNativeJS: __guard@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:8091:15 12-11 18:00:37.863 25690 30527 W ReactNativeJS: invokeCallbackAndReturnFlushedQueue@http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false:7933:21 12-11 18:00:37.863 25690 30527 W ReactNativeJS: invokeCallbackAndReturnFlushedQueue@[native code]

screen shot 2018-12-11 at 6 04 35 pm

Could not resolve all artifacts for configuration ':react-native-audio-recorder-player:classpath'.

Version of react-native-audio-recorder-player

react-native-audio-recorder-player: 2.2.0

Platforms you faced the error (IOS or Android or both?)

Android

Expected behavior

record voice after installing package.

Actual behavior

it appearing error after installing package and then running project.

Screenshot 2019-07-15 at 3 48 10 PM

Steps to reprodue the behabior

just install package and re run project by react-native run-android

No re-render component when using startPlayer().

Version of react-native-audio-recorder-player: ^2.1.2

Platforms you faced the error (IOS or Android or both?): Android

Expected behavior: re-render component when setState

Actual behavior Not re-renderer until startPlayer completed

Steps to reprodue the behabior

TypeError: Cannot read property 'stopRecorder' of undefined

I can see the audio player when I press play it says it is undefined.
It works just fine on Android.

I have checked everywhere (all the files) to see if that is a linking issue and found that it is not showing up in products in pod folder (Attached screenshot below) but not sure it is happening due to the same or not.

Version of react-native-audio-recorder-player: 2.2.2

Platforms you faced the error (IOS or Android or both?)
IOS

Expected behavior
Start recording

Screen Shot 2019-08-05 at 6 04 50 PM

TypeError: Cannot read property 'startRecorder' of undefined

I can see the audio player when I press play it says its undefined.
It works just fine on Android.
I have posted a picture to showcase what it is doing.

I have checked everywhere (all the files) to see if that is a linking issue but its not.

Version of react-native-audio-recorder-player

Version of player: 2.1.2

Platforms you faced the error (IOS or Android or both?)

IOS

Expected behavior

Start recording

Actual behavior

image

Steps to reproduce the behaviour

Pretty standard steps as described.
Only difference I guess is our react native version.

I am using "react-native": "0.58.6",

Record audio in mp3 format

Hello, guys!!!

I need a solution to record the mp3 audio. Your library only allows recording in mp4 format, which is not supported by the IBM Speech to Text api. I'm developing an android app with react native.

Can not start recording, getting warning of setSubscriptionDuration.

Version of react-native-audio-recorder-player

"react-native-audio-recorder-player": "^2.0.8",
"react": "^16.5.1",
"react-native": "0.57.0",

Platforms you faced the error (IOS or Android or both?)

  • Android

Getting following types of warning and can not start record an audio, I have given run-time permissions for the record an audio too..

device-2018-10-02-172949

I have shared my code too.

import React, {Component} from 'react';
import {
StyleSheet,
Text, Button,
PermissionsAndroid,
View, TouchableOpacity, StatusBar
} from 'react-native';
import AudioRecorderPlayer from 'react-native-audio-recorder-player';

export default class AudioRecord extends React.Component<> {

audioRecorderPlayer: AudioRecorderPlayer;

constructor(props) {
    super(props);
    this.state = {
        emailText: "",
        password: ""
    };
    this.audioRecorderPlayer = new AudioRecorderPlayer();
    this.audioRecorderPlayer.setSubscriptionDuration(0.09); // optional. Default is 0.1
}

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)),
        });
    });
};

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

onStartPlay = async () => {
    const msg = await this.audioRecorderPlayer.startPlayer();
    this.audioRecorderPlayer.addPlayBackListener((e) => {
        if (e.current_position === e.duration) {
            this.audioRecorderPlayer.stopPlayer();
        }
        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 () => {
    this.audioRecorderPlayer.stopPlayer();
    this.audioRecorderPlayer.removePlayBackListener();
};

render() {
    return (
        <View style={styles.imageStyle} >
            <StatusBar
                backgroundColor='#BCE1FE'
                barStyle="light-content"
            />

            <View style={{flex:1,flexDirection:'row'}}>
                <TouchableOpacity
                    activeOpacity = { .5 }
                    onPress={() => this.onStartRecord()}>
                    <Text style={[styles.signup,{color:'black',fontSize:16}]}>onStartRecord</Text>
                </TouchableOpacity>
            </View>

            <View style={{flex:1,flexDirection:'row'}}>
                <TouchableOpacity
                    activeOpacity = { .5 }
                    onPress={() => this.onStopRecord()}>
                    <Text style={[styles.signup,{color:'black',fontSize:16}]}>onStopRecord</Text>
                </TouchableOpacity>
            </View>

            <View style={{flex:1,flexDirection:'row', marginTop:10}}>
                <TouchableOpacity
                    activeOpacity = { .5 }
                    onPress={() => this.onStartPlay()}>
                    <Text style={[styles.signup,{color:'black',fontSize:16}]}>onStartPlay</Text>
                </TouchableOpacity>
            </View>

        </View>
    );
}

}

const styles = StyleSheet.create({
container: {
backgroundColor: '#0ED2F7',
},
imageStyle: {
flex: 1, backgroundColor: '#0ED2F7', alignItems: 'center'
},
inputBox: {
width: 300,
borderRadius: 25,
borderColor:'#19295c',
borderWidth: 2,
paddingHorizontal: 16,
fontSize: 16,
color: '#19295c',
marginVertical: 10
},
welcome: {
fontSize: 20,
textAlign: 'center',
color: '#333333',
margin: 20,
},
signup: {
fontSize: 15,
textAlign: 'center',
color: '#333333',
marginTop:50,
marginLeft:5
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
button: {
width: 300,
backgroundColor: '#19295c',
borderRadius: 25,
marginVertical: 10,
paddingVertical: 13
},
buttonText: {
fontSize: 16,
fontWeight: '500',
color: '#ffffff',
textAlign: 'center'
}
});

New logo/icon proposal

Good day Sir I am a graphic designer and i am interested in designing a logo for your good project. I will be doing it as a gift for free. I just need your permission first before i begin my design. Hoping for your positive feedback. Thanks

Audio Recorder Player PodSpec Failed

Version of react-native-audio-recorder-player

2.1.4

Platforms you faced the error (IOS or Android or both?)

I try to add manually the dependencies to my podfile
pod 'RNAudioRecorderPlayer', :path => '../node_modules/react-native-audio-recorder-player/ios'

Expected behavior

Supposed to work

Actual behavior

Analyzing dependencies Fetching podspec for RNAudioRecorderPlayerfrom../node_modules/react-native-audio-recorder-player/ios[!] TheRNAudioRecorderPlayerpod failed to validate due to 1 error: - ERROR | attributes: Missing required attributehomepage. - WARN | source: The version should be included in the Git tag. - WARN | description: The description is equal to the summary.

Steps to reprodue the behabior

Warning Error: mediaPlayer is null when called stopPlayer funtion

Version of react-native-audio-recorder-player

2.0.8

Platforms you faced the error (IOS or Android or both?)

Android 8.0.0

Expected behavior

When calls the stopPlayer() function, It's work fine, but show a warning that is annexed below

Actual behavior

Don't show warning when call stopPlayer function

Steps to reprodue the behabior

call stopPlayer()

Here is my code:

startPlay function

 this.recorderPlayer.addPlayBackListener(e => {
    if (e.current_position === e.duration) {
        this.stopPlay()
        return
    }
    return
  })

stopPlay funtion

stopPlay = () => {
    this.recorderPlayer.stopPlayer()
    this.recorderPlayer.removePlayBackListener()
}


war

file is not generated/saved after stop recording

Version : 2.1.2

Platforms you faced the error: Android

Expected behavior: file is not generated/saved after stop recording and hence not able to upload using multipart request

Actual behavior: File should get generated in the device in the specified path

Steps to reproduce the behavior :

  1. record audio in android
  2. stop recording
  3. check file at path you specified while recording

seekToPlayer() param is not milliseconds but seconds

When I pass millisecond as a parameter to seekToPlayer (), current_position is equal to duration in the callback function of addPlayBackListener.
  So, when I pass the seconds to the parameter in seekToPlayer (), the current_position is passed normally.

Can't install package

i am trying to install the packages, but not installing

react-native-cli: 2.0.1
react-native: 0.57.8
npm: 6.6.0
yarn: 1.12.3

command : npm install react-native-audio-recorder-player --save

screen shot 2019-02-02 at 11 13 31 pm

Can only play on the same platform as recorded on.

Version of react-native-audio-recorder-player

2.0.8

Platforms you faced the error (IOS or Android or both?)

Both

Expected behavior

Files are playable on both platforms.

Actual behavior

Audio file only playable on the platform it was recorded on.

Steps to reproduce the behavior

Standard path records .m4a on ios and .mp4 on Android, but they are only playable on that same platform (if uploaded to a server and downloaded to the other platform's app).

Is there any universal sound format that can work across platforms?

Resume Record Functionality.

Version of react-native-audio-recorder-player

2.0.8

Platforms you faced the error (IOS or Android or both?)

Both

Expected behavior

I am trying to pause the recorder and then resume it back again. I am not able to do that with the current set of APIs.
Is there a way to do this ?

Thanks in advance

IOS does not play local mp3 files

Version of react-native-audio-recorder-player

2.0.8

Platforms you faced the error (IOS or Android or both?)

IOS

Expected behavior

Audio plays

Actual behavior

Audio does not play

Steps to reprodue the behabior

Play a local mp3 file where path looks something like: /Users/[user]/Library/Developer/CoreSimulator/Devices/5555-5555-5555/data/Containers/Data/Application/5555-5555-5555/Documents/tracks/track.mp3

Does not work with file:// prepended to the path either.

Uri Has two // insist of three

when I use startRecorder() function return uri . but this uri is not usable for Upload.
my solution is to use replace function like below
const newUri=result.replace('file://','file:///')
and its work fine on android
my question is this trick works on ios or Not .

const result = await this.audioRecorderPlayer.startRecorder() 이 작동하지 않습니다.

<안드로이드 이슈>
image
image

현재 manifest 권한 설정을 모두 해준 상태이며, React-native 57.0, React 16.5.0 사용하고 있습니다.
아 그리고 현재 안드로이드 폰에 SD Card는 따로 사용하지 않습니다.

위 사진과 같이 default 경로에 대해 권한이 없다고 나옵니다. 그래서 다른 경로로 설정해줬는데, no such file and directory 같은 에러가 나옵니다.

어떤 경로로 설정해줘야 할까요?

Problem

Sometimes I save my code and try to play a new audio it appears on my console "You can use the camera" ... And when I try to press the pause, it returns me this error

46744427_193766478230532_4579644419937927168_n

Playing twice

Version of react-native-audio-recorder-player ^2.1.4

Platforms you faced the error (IOS or Android or both?) Android

Expected behavior Play the audio i want

Actual behavior Play the previous audio not the one i want

Steps to reprodue the behabior

image

Before this code, i have played the audio from URI and then i pause it. Then i played another one in phone's storage but it still played the previous audio from URI.

I logged the console above and the result was "Player resumed"

image

Please help, thanks in advance !

Not saving file when stopRecording()

Version 2.0.8

iOS

Save file audio.m4a

Not saving file, i search it by browsing in the path, and with RNFS seaching in the path, system cant find the file: The file “sound.m4a” couldn’t be opened because there is no such file.

Following the example

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.