Giter VIP home page Giter VIP logo

react-native-audio's Introduction

Record audio in iOS or Android React Native apps.

MAINTENANCE STATUS

This project is no longer actively maintained by me, the original author. I will not be answering issues or merging any more PRs. If someone is interested in taking over the library permanently, let me know!

BREAKING CHANGES

For React Native >= 0.47.2, use v3.4.0 and up. For React Native >= 0.40, use v3.1.0 up til 3.2.2. For React Native <= 0.39, use v3.0.0 or lower.

v4.0 introduced a breaking change to the API to introduce distinct pause and resume methods.

v3.x removed playback support in favor of using more mature libraries like react-native-sound. If you need to play from the network, please submit a PR to that project or try react-native-video.

Installation

Install the npm package and link it to your project:

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

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

Manual Installation

This is not necessary if you have used react-native link

Android

Edit android/settings.gradle to declare the project directory:

include ':react-native-audio'
project(':react-native-audio').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-audio/android')

Edit android/app/build.gradle to declare the project dependency:

dependencies {
  ...
  compile project(':react-native-audio')
}

Edit android/app/src/main/java/.../MainApplication.java to register the native module:

...
import com.rnim.rn.audio.ReactNativeAudioPackage; // <-- New
...

public class MainApplication extends Application implements ReactApplication {
  ...
  @Override
  protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new ReactNativeAudioPackage() // <-- New
    );
  }

iOS

Drag node_modules/react-native-audio/ios/RNAudio.xcoderproj into your project's Libraries on Xcode.

Add libRNAudio.a into Link Binary With Libraries from Xcode - Build Phases.

Running the Sample App

In the AudioExample directory:

npm install
react-native run-ios
react-native run-android

Usage

To record in AAC format, at 22050 KHz in low quality mono:

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

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

AudioQuality is supported on iOS. Low, Medium, and High will translate to AVAudioQualityLow, AVAudioQualityMedium, and AVAudioQualityHigh respectively.

Cross-platform options

SampleRate: int
Channels: int
AudioQuality: string
AudioEncoding: string
IncludeBase64: boolean

Encodings supported on iOS: lpcm, ima4, aac, MAC3, MAC6, ulaw, alaw, mp1, mp2, alac, amr Encodings supported on Android: aac, aac_eld, amr_nb, amr_wb, he_aac, vorbis

Use the IncludeBase64 boolean to include the base64 encoded recording on the AudioRecorder.onFinished event object. Please use it with care: passing large amounts of data over the bridge, from native to Javascript, can use lots of memory and cause slow performance.

If you want to upload the audio, it might be best to do it on the native thread with a package like React Native Fetch Blob.

iOS-only fields

Use MeteringEnabled boolean to enable audio metering. The following values are available on the recording progress object.

Name Related AVAudioRecorder parameter Description
currentMetering averagePowerForChannel The current average power, in decibels, for the sound being recorded. A return value of 0 dB indicates full scale, or maximum power; a return value of -160 dB indicates minimum power (that is, near silence). If the signal provided to the audio recorder exceeds ±full scale, then the return value may exceed 0 (that is, it may enter the positive range).
currentPeakMetering peakPowerForChannel The current peak power, in decibels, for the sound being recorded. A return value of 0 dB indicates full scale, or maximum power; a return value of -160 dB indicates minimum power (that is, near silence). If the signal provided to the audio recorder exceeds ±full scale, then the return value may exceed 0 (that is, it may enter the positive range).

For example:

AudioRecorder.onProgress = (data) => {
    console.log(data.currentMetering, data.currentPeakMetering)
};

Android-only fields

AudioEncodingBitRate: int

OutputFormat: string, mpeg_4, aac_adts, amr_nb, amr_wb, three_gpp, webm

AudioSource: int (constants) (Possible values: AudioSource.DEFAULT, AudioSource.MIC, AudioSource.VOICE_UPLINK, AudioSource.VOICE_DOWNLINK, AudioSource.VOICE_CALL, AudioSource.CAMCORDER, AudioSource.VOICE_RECOGNITION, AudioSource.VOICE_COMMUNICATION, AudioSource.REMOTE_SUBMIX, AudioSource.UNPROCESSED)

See the example for more details. For playing audio check out React Native Sound

MP3 recording is not supported since the underlying platforms do not support it.

Thanks to Brent Vatne, Johannes Lumpe, Kureev Alexey, Matthew Hartman and Rakan Nimer for their assistance.

Progress tracking code borrowed from https://github.com/brentvatne/react-native-video.

react-native-audio's People

Contributors

akio0o avatar brodanoel avatar brunsy avatar cooperka avatar dannyyaou avatar getsetbro avatar hartmamt avatar hikouki avatar jsierles avatar ketn avatar lefnire avatar liamse avatar n1ru4l avatar neilsarkar avatar noitidart avatar omarbasem avatar pablogs9 avatar phanalpha avatar rakannimer avatar rcchen avatar sermler avatar shivamkjjw avatar simonerm avatar stevenmasini avatar tommoor avatar ufolux avatar vaukalak avatar wbroek avatar wootwoot1234 avatar zhangtaii 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-audio's Issues

Can't record .mp3?

This is my code:
var audioPath = AudioUtils.DocumentDirectoryPath + '/test.mp3';
console.log(audioPath);
var options = {
AudioEncoding: '.mp3'
};
AudioRecorder.prepareRecordingAtPath(audioPath, options);

but in xcode in found fllow error:

error: The operation couldn’t be completed. (OSStatus error 1718449215.)

what can i do?

What is the correct path

Hi,
I am a bit lost. If I put my sound file in /Users/jerome/my_react_native_project_root_folder/src/sounds/sound.m4a
how should I play it?

I tried many different combination (and file extension caf, wav, m4a) with AudioUtils.DocumentDirectoryPath and AudioUtils.MainBundlePath. Somehow I always ends up with the sound not been played and the log:

audio playback loading error: The operation couldn’t be completed. (OSStatus error 2003334207.)

I checked the error log in the issues but I could not find an example on how to play a sound that you put in your project (Note that the recorder works perfectly and I can play the file send by the recorder as the recorder give you the full path, I just would like to use this react-native-audio to also play file that I would share in iOS and Android, so for avoiding duplicate they should be in the react native project folders).

cheers,
jerome

How to play the local resources

// MainBundlePath: AudioPlayerManager.MainBundlePath,
// CachesDirectoryPath: AudioPlayerManager.NSCachesDirectoryPath,
// DocumentDirectoryPath: AudioPlayerManager.NSDocumentDirectoryPath,
// LibraryDirectoryPath: AudioPlayerManager.NSLibraryDirectoryPath,

Who can help me

Audio playback loading error

Thanks for taking the time to make this, unfortunately I haven't been able to get it to work.

Same error regardless of if I'm using the included example or installing it into an existing project.

2015-05-15 17:23:03.765 AudioExample[7161:1797587] audio playback loading error: The operation couldn’t be completed. (OSStatus error 2003334207.)

Also receive warnings for both AudioRecorderManager.m and AudioPlayerManager.m.

#AudioRecorderManager.m:
/Users/Chad/Documents/Work/Dev/react-native-audio/AudioRecorderManager.m:43:13: Unused variable 'time'
#AudioPlayerManager.m:
/Users/Chad/Documents/Work/Dev/react-native-audio/AudioPlayerManager.m:38:13: Unused variable 'time'
/Users/Chad/Documents/Work/Dev/react-native-audio/AudioPlayerManager.m:80:9: Format string is not a string literal (potentially insecure)

Thanks in advance for the help.

Can not use the audioplayer just before calling an audiorecorder method (it works on Simulator though)

It can be reproduce on the current AudioExample on an iPhone 5c (everything does work fine on the simulator - I suspect the simulator been too fast to have the problem):

Add the AudioPlayer:
import {AudioRecorder, AudioPlayer, AudioUtils} from 'react-native-audio';

Then in
_record() {
AudioPlayer.play(AudioUtils.MainBundlePath + '/start.m4a'); // New line - the file is added to the root folder of the xcode project checking copy and target.
AudioRecorder.startRecording();
this.setState({recording: true, playing: false});
}

On simulator, no issues. On iPhone5c the sound is played but then the timer stay at 0.

Additionally, sometime the iPhone5c records properly (with the timer working one time), but once the recording finishes I played another sound (success.m4a) and then when I try to press Play, I have the same problem. The recording is not played and the onprogress is called only once and the currentTime is equal 0 when you console.log in the onProgress - which is weird as when things work the currentTime is never equal to 0 when you console.log it in the onProgress. (all is still working fine in the simulator)

I confirm that without playing a sound before calling a AudioRecording function, the AudioExample works perfectly on iPhone5c.

I am thinking making the play function of the AudioPlayer returning a promise but it looks more like a patch than fixing the original issue (maybe it will not even work though, I am looking on how to create a promise in JS :)). I thought that maybe you would know what happen and help me to go in the right direction to fix it :)

Error loading mp3, npm start

transforming [======================================= ] 99% 539/546TypeError: unsupported file type
    at lookup (/Users/user/Dev/app/app/node_modules/image-size/lib/index.js:35:9)
    at /Users/user/Dev/app/app/node_modules/image-size/lib/index.js:93:22
    at /Users/user/Dev/app/app/node_modules/image-size/lib/index.js:50:9
    at /Users/user/Dev/app/app/node_modules/graceful-fs/graceful-fs.js:43:10
    at FSReqWrap.oncomplete (fs.js:82:15)

It works fine if I put my mp3 file outside the project scope (on my Desktop for instance) and I just load by '/Users/user/Desktop/abc.mp3', but when I move the mp3 file into my project, it throws this error 0_o

Unused Entity Issue - Xcode Warning for variable time

Hi Joshua, Thanks for putting together this package. Really appreciate it. Xcode 6.4 is giving me an "Unused Entity Issue" warning for variable "time" in both AudioRecorderManager.m and AudioPlayerManager.m. I don't see this variable being used in the code. Perhaps I'm missing something here? Thanks.

AudioRecorderManager.checkAuthorizationStatus - Undefined is not an object

I keep getting this error when I try and import the module. I thought it could be a version issue but it seems like all of the versions have the same problem. It's strange though, because when I download the AudioExample it works great. When I copy the index.ios.js file from the AudioExample and paste the contents into my project it no longer works - Any suggestions would be greatly appreciated!

Method to retrieve the recorded file url

I'm trying to get the url of the file once it is recorded to upload to a server endpoint, it looks as though this is not currently exposed. Is there a way to get it that I'm missing perhaps? The path isn't enough.

NPM out of date

The version currently published on NPM includes bugs which have been fixed here - are you able to bump the version and republish?

Stop any and all audio

So I don't how common a circumstance this is, but in my flashcard app, each card has an audio file. If I hit play on one (and some of these are long files), then change my navigation and then return, it doesn't let me cut off the audio. Any suggestions?

AudioRecorder.onProgress not working when device is locked

I am trying to check the progress of an audio recording while the app is locked. It works fine in the simulator but not on my test device (5s). I have these lines of code that works as expected when app is running or in background on the device:

AudioRecorder.onProgress = (data) => { console.log("Tracking audio recording..."); doStuff(); };

I notice that the console stops logging once the device is locked. It will start again if I press the home button. Is this behavior expected or some setting that I have enabled on my device.

Thanks,
Nick

Unhandled JS Exception: undefined is not an object (evaluating 'AudioRecorderManager.checkAuthorizationStatus')

I get this error after load app.

Unhandled JS Exception: undefined is not an object (evaluating 'AudioRecorderManager.checkAuthorizationStatus')

I look source of react-native and not found the module 'AudioRecorderManager'

componentDidMount() {
        let audioPath = AudioUtils.DocumentDirectoryPath + '/test.aac'

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

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

        AudioRecorder.onFinished = (data) => {
            this.setState({ record: audioPath })
        }
    }

buildRecord() {
        let buttonPlay = this.state.record?
            <Button rounded style={ Style.buttonPlay } onPress={ () => {
                AudioRecorder.playRecording()
            }}>
                <Icon name="ios-play" />
            </Button>: null

        return (
            <View style={ Style.containerDescription }>
                <Button rounded style={ Style.buttonRecord } onPress={ AudioRecorder.startRecording() }
                    onPressOut={ AudioRecorder.stopRecording() }>
                    <Icon name="ios-microphone" />
                </Button>
                { buttonPlay }
            </View>
        )
    }

About react

"react": "~15.2.1",
"react-native": "^0.31.0",

iOS stops playing audio after stop recording

When I stop a recording on my iPad Air device, I get the error below:

ERROR: [0x16e247000] AVAudioSession.mm:692: -[AVAudioSession setActive:withOptions:error:]: Deactivating an audio session that has running I/O. All I/O should be stopped or paused prior to deactivating the audio session.

And after that all audio played is silent.

When I'm in the iOS simulator I have no problems, recordings stop as expected and everything seems to work perfectly.

I'm playing sound effects within an React Native iOS WebView (using Howler.js v2.0.0) immediately before and after recording, so maybe that's part of the problem?

Android support?

Hi, is there an appetite for this project to support Android?

Multiple recordings?

How would I record and playback multiple files (either at the same time or only one at a time)?

loop

I needed to loop an audio file so I just added [_audioPlayer setNumberOfLoops:-1].
Should I PR 'loop' as an optional argument to play and playWithUrl?

Possible data visualization

This is probably out of the scope of this project, but how would I get a data visualization of the recorded audio, or audio that is preloaded into the project and played via the AudioPlayer? I have created a SO question here. Any suggestions would be very welcome. If it isn't within the scope of the project feel free to close the issue. Thank you :)

AudioRecorder.onFinished never invoked

run example application, if I understand correctly afterAudioRecorder.stopRecording() a method called AudioRecorder.onFinished should be invoked.

Right now it's never invoked in the example application. Looking to native code, it should be called after audioRecorderDidFinishRecording which seems to be never invoked.

I need that to check, that the file has been recorded.

Playback of .mp3 files supported? Volume supported?

Hey!

I just wanna ask, if I can use this module to just play pure mp3 files of my own? This is not obvious through the example, because you just play your recordings there.

Next question: Is there some kind of volume control?

thanks for your answers!

Cheers,
Klaus

Accessing recorded file

I understand that the 'storage of recorded file into media library' feature is part of your to-do list.
Meanwhile, is there a way to access the recorded file ?

I am intending to upload the recorded file online.

AudioRecorder.pausePlaying(); missing

It looks as though there is a method missing from the Audio example. I don't see it on the Audio.ios.js. Assuming that I should be calling AudioPlayerManager.pause();

Added encoding option to recording

I added an encoding option to recording. I had a hard time figuring out which encoding type to use for .caf files. You used a hard coded number, 16 which I think translates to kAudioFormatMPEGLayer2. That might be worth double checking. I tried to create a pull request but I can't figure out how to just pull this commit (wootwoot1234@43df597) and not all the changes in my fork. Hope it helps.

Upgrading to use w/ React Native 0.4.4

0.4.3+ has changed the way chrome debugging works. It's now requires the new WebSockets Library.

To make the example project work:

  1. Prior to running npm install in AudioExample, update the example's package.json to ("react-native": "^0.4.4")
  2. Run npm install
  3. Remove RCTWebSocketDebugger.xcodeproj from your project
  4. Add WebSocket library from node_modules/react-native/Libraries/WebSocket/*.xcodeproj
  5. Link the libRCTWebSocket.a to your project ("Link Binary with Libraries" under your project's "Build Phases").

Hope this helps someone.

Recording configurations

Add remaining configurable options: bitrate and AVSession category. Send options via an object rather than tons of parameters.

audio playback loading error

I ran the AudioExample project. After pressing RECORD, STOP and PLAY, I get

2016-04-01 03:14:24.691 AudioExample[5087:2446864] audio playback loading error: The operation couldn’t be completed. (OSStatus error 2003334207.)

I'm using

react-native -v
react-native-cli: 0.1.10
react-native: 0.21.0

how support mp3

how to support MP3 recording on iOS? this maybe a common use!
help!!!

Questions about getting started

So I tried to use the project in 2 ways. When I tried to clone the project, npm install, and run, I got several errors. Xcode tells me: <Error>: CGContextTranslateCTM: invalid context 0x0.. I post some screenshots below to debug better.

Second, when I follow the installation instructions, on simply adding the 4 AudioPlayer/AudioRecorderManager files in my project, I find that they aren't loading as NativeModules. I tested this by console.logging the NativeModules, and the AudioPlayerManager and AudioRecorderManager were not included.

Any suggestions? Thank you! Below are screenshots to help see the problems more clearly.
screen shot 2015-10-17 at 2 48 50 pm
screen shot 2015-10-17 at 2 48 37 pm
screen shot 2015-10-17 at 2 48 32 pm

record volume

how i get a volume wave when recording?
where i get the data of volume about?

No software license

Without a software license this software is not legally allowed to be used for any purpose without the express written permission of the author. Please choose a license and add the license file to the code. Conveniently http://choosealicense.com makes the process easy and fast.

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.