Giter Club home page Giter Club logo

react-native-audio-record's Introduction

react-native-audio-record

Audio record buffers for iOS and Android.

Install

yarn add react-native-audio-record
react-native link react-native-audio-record

Usage

import AudioRecord from 'react-native-audio-record';

const options = {
  sampleRate: 16000,  // default 44100
  channels: 1,        // 1 or 2, default 1
  bitsPerSample: 16,  // 8 or 16, default 16
  audioSource: 6,     // android only (see below)
  wavFile: 'test.wav' // default 'audio.wav'
};

AudioRecord.init(options);

AudioRecord.start();

AudioRecord.stop();
// or to get the wav file path
audioFile = await AudioRecord.stop();

AudioRecord.on('data', data => {
  // base64-encoded audio data chunks
});

For audioSource use one of the constant values from here. Default value is 6 (VOICE_RECOGNITION).

Use 3rd-party module like buffer to decode base64 data. Example -

// yarn add buffer
import { Buffer } from 'buffer';
chunk = Buffer.from(data, 'base64');

Don't forget to add microphone permission in your app.

Example

Example folder contain sample apps for recording (using this module) and playback (using 3rd party modules)

Credits/References

I'm not a native app developer. Most of the code is taken from online resources.

react-native-audio-record's People

Contributors

actondev avatar dependabot[bot] avatar is343 avatar marcelbreasway avatar vinayr 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

react-native-audio-record's Issues

Getting information from buffer

So I am interested in this part here const chunk = Buffer.from(data, 'base64');. Would it be possible to get real-time information like amplitude by looking at each chunk?

Set volume of recording

I use react-native-sound to play the sound recorded, the volume is too low. Is there any method to increase the volume?

file size 0 if bitPerSample is 8

Here are my options:
sampleRate: 11025,
channels: 1,
bitsPerSample: 8,
wavFile: 'test.wav'

After recording the test.wav size is 0. If I set bitsPerSample as 16, it works fine. Can anyone take a look at this issue? Thanks

Play audio from buffer

Hi all,

I am trying to join buffer and playback it. Does anyone have a idea for this case.

Thanks in advance.

startRecording Error of uninitialized AudioRecord Method

I am trying to create audio recorder on android i faced this error

const options = { sampleRate: 16000, channels: 1, bitsPerSample: 16, audioSource: 6, wavFile: 'test.wav' }
AudioRecord.init(options); AudioRecord.start();

React-native --v: 57.8

error

Wrong promise resolving on android

When calling stop, the Android implementation calls promise.resolve() even before the file is actually is saved. This leads to unexpected behavior

  • running the app for the first time
  • calling stop()
  • immediately trying to read the file results to an exception, as the file is not ready yet.

file isnt saved

After recording i can the file from react-native-sound giving it the audioFile path returned by AudioRecord.stop() function but i cant see the file anywhere in my phone?
plz help me!

Storing base64 data in a variable

Recording is working however, I'm trying to store the data that I'm receiving through

AudioRecord.on('data', data => {
  // base64-encoded audio data chunks
});

in a variable. However, it's not working for some reason and I'm really struggling with this.
I've tried doing this (within a function):

var tempString = '';
AudioRecord.on('data', data => {
  tempString += data;
});

but it only gives the first part of the data. If I just set it to the data and output it, it does gives different data but never when I try to add all the data together. I've tried arrays, listening to a changing variable and using another function but for some reason they all just gave the first data that is received if I used a similar method to the one I described above.
So how do I store all the data that I get from a 3 second audio recording in a variable?

New Release Roadmap

Looking at the last release I got curious whether a new release is planned. Also, is it because there is a alternative project that is more actively developed?

This lib records internal audio?

Title is the basically the question,I just want to know if this lib would record something like a spotify music playing internally and not using the outside microphone.

Could not find declaration file for module 'react-native-audio-record'

Hi all,

After installing and linking in react-native v0.58.4 :

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

I get the following error message after importing:
import AudioRecord from 'react-native-audio-record';

1

I'm fairly new to this, so could anyone point me in the right direction? I have tried implementing the code as explained in the 'Usage' section to see if it would run. However I get the following error:

screenshot_20190218-145309

null is not an object (evaluating 'RNAudioRecord.init')

Hi there,

I am getting this error:

[Unhandled promise rejection: TypeError: null is not an object (evaluating 'RNAudioRecord.init')]
at node_modules/react-native-audio-record/index.js:7:43 in AudioRecord.init
at components/AudioTest.tsx:38:20 in recordSound

In AudioTest.tsx I just have a button that calls the following method (basically copied from the README):

import AudioRecord from "react-native-audio-record";

...

async function recordSound() {
  await PermissionsAndroid.requestMultiple([
    PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
  ]);
    
  const options = {
    sampleRate: 16000,  // default 44100
    channels: 1,        // 1 or 2, default 1
    bitsPerSample: 16,  // 8 or 16, default 16
    audioSource: 6,     // android only (see below)
    wavFile: 'test.wav' // default 'audio.wav'
  };

  AudioRecord.init(options); // <--- error happens here
  
  AudioRecord.start();
  
  AudioRecord.stop();
  // or to get the wav file path
  let audioFile = await AudioRecord.stop();
  
  AudioRecord.on('data', data => {
    console.log('data');
    // base64-encoded audio data chunks
  }); 
}

Can you tell me what I am doing wrong?


I am using expo
on Android
versions "react-native-audio-record": "^0.2.2"

pause functionality

Hi,

Thanks for your amazing work this is by far the best package I have found for audio recording with React Native. This isn't an issue more a question about features. Do you plan on adding a pause functionality in the near future?

'React/RCTEventEmitter.h' file not found

Hi,
After adding the package I am starting to get this error when build in Xcode.
When I try to build for iOS I am getting this error.
Has anyone faced it before?
Screenshot 2019-09-11 at 10 33 50

I want to change AudioFileFlags

I want to change AudioFileFlags of AudioFileCreateWithURL function.
In kAudioFileFlags_EraseFile, unnecessary FLLRs are inserted in the header.
If you specify kAudioFileFlags_DontPageAlignAudioData, FLLR will not be inserted in the header.
You need a file without FLLR.

I hope that it can be specified as an option.

Android crash

setAudioSource failed.
setAudioSource
MediaRecorder.java
start
RNSoundRecorderModule.java:108
invoke
Method.java
invoke
JavaMethodWrapper.java:372
invoke
JavaModuleWrapper.java:160
run
NativeRunnable.java
handleCallback
Handler.java:790
dispatchMessage
Handler.java:99
dispatchMessage
MessageQueueThreadHandler.java:29
loop
Looper.java:164
run
MessageQueueThreadImpl.java:192
run
Thread.java:764

not record to a file

Hi this is not an issue. I am wondering whether I can only listen to the mic but not save it to a file. Basically I want to use

AudioRecord.on('data', data => {
  // base64-encoded audio data chunks
}); 

without save the file to my phone. Is it possible? Thanks

Cannot resolve symbol goodatlas

After linking the package, this import statement cannot be resolved.

import com.goodatlas.audiorecord.RNAudioRecordPackage

package com.goodatlas.audiorecord does not exist

Cannot find symbol new RNAudioRecordPackage()

Thanks.

TypeError: undefined is not an object(evaluating '_reactNativeAudioRecord.AudioRecord.init')

My code is almost same as App1.js but i'm getting warning as TypeError: undefined is not an object(evaluating '_reactNativeAudioRecord.AudioRecord.init') when i'm calling init and also similar warning for other calls (start(),stop() etc.) .Also I'm getting undefined from stop( ) call which should return path of the audio file.
My Code:-
class App extends Component {
sound = null;
state = {
audioFile: '',

recording: false,

loaded: false,

paused: true
};
async componentDidMount() {
await this.checkPermission();
// await this.checkPermission1();
// await this.checkPermission2();
const options = {
sampleRate: 16000,

channels: 1,

bitsPerSample: 16,

audioSource: 1,

};

AudioRecord.init(options);
// AudioRecord.on('data', data => {

// const chunk = Buffer.from(data, 'base64');

// console.log('chunk size', chunk.byteLength);

// // do something with audio chunk

// });
}
checkPermission = async () => {
try {
const granted = await PermissionsAndroid.requestMultiple(
[PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,PermissionsAndroid.PERMISSIONS.RECORD_AUDIO],
{
title: "Audio Recording Permission",
message:"PERSMISSION RO RECORD AUDIO",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the camera");
} else {
console.log("Camera permission denied");
}
} catch (err) {
console.warn(err);
}
};
start =async () => {
console.log('start record');

this.setState({ audioFile: '', recording: true, loaded: false });

AudioRecord.start();
};
stop = async () => {
if (!this.state.recording) return;

console.log('stop record');
try{
var audioFile = await AudioRecord.stop();
}
catch(err){
console.warn(err);
}
console.log('audioFile', audioFile);

this.setState({ audioFile, recording: false });
};
load = () => {
return new Promise((resolve, reject) => {

if (!this.state.audioFile) {

return reject('file path is empty');

}

this.sound = new Sound(this.state.audioFile, '', error => {

if (error) {

  console.log('failed to load the file', error);

  return reject(error);

}

this.setState({ loaded: true });

return resolve();

});

});
};
play = async () => {
if (!this.state.loaded) {

try {

await this.load();

} catch (error) {

console.log(error);

}

}

this.setState({ paused: false });

Sound.setCategory('Playback');

this.sound.play(success => {

if (success) {

console.log('successfully finished playing');

} else {

console.log('playback failed due to audio decoding errors');

}

this.setState({ paused: true });

// this.sound.release();

});
};
pause = () => {
this.sound.pause();

this.setState({ paused: true });
};
render() {
const { recording, paused, audioFile } = this.state;

return (

<View style={styles.row}>

  <Button onPress={this.start} title="Record" disabled={recording} />

  <Button onPress={this.stop} title="Stop" disabled={!recording} />

  {paused ? (

    <Button onPress={this.play} title="Play" disabled={!audioFile} />

  ) : (

    <Button onPress={this.pause} title="Pause" disabled={!audioFile} />

  )}

</View>

);
}
import:-
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import React, { Component, useState,useEffect } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
TextInput,
TouchableHighlight,
Platform,
PermissionsAndroid,
} from 'react-native';
import {AudioRecord} from 'react-native-audio-record';
import Sound from 'react-native-sound';
// We are importing the native Java module here
import { Buffer } from 'buffer';
import {NativeModules} from 'react-native';
import RadioForm, {RadioButton, RadioButtonInput, RadioButtonLabel} from 'react-native-simple-radio-button';
Could someone look into this issue and provide possible fix?

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

Error creating AudioRecord instance Android

hi, i got this error from Android, can u help:

2022-08-27 15:33:54.502 7983-8041 E/AudioRecord: createRecord_l(0): AudioFlinger could not create record track, status: -1
2022-08-27 15:33:54.502 7983-804 E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -1.

startRecording() called on an uninitialized AudioRecord [Android]

this issue generated only on android, only at the first time,
any suggestions about how to avoid this issue

code example below

      const options = {
		sampleRate: 16000,  // default 44100
		channels: 1,        // 1 or 2, default 1
		bitsPerSample: 16,  // 8 or 16, default 16
		audioSource: 6,     // android only (see below)
		wavFile: 'chat_voice_record.wav' // default 'audio.wav'
	};

      AudioRecord.init(options);

     async function startRecording() {
            const res = await checkMicrophonePermissions(); // check microphone permissions 
            if(!res.ok) return; // check permissions granted
            AudioRecord.start();
     }

Silence detection

Is it possible to detect silence? Specifically in:

AudioRecord.on('data', data => {
  // base64-encoded audio data chunks
  // Check whether this data instance is silent or not
});

If anybody knows some method to detect silence (that works in React Native) in base64 data kindly share!

java.lang.IllegalStateException crash on Huawei P30 Pro with Android 9

Device: Huawei P30 Pro
OS: Android 9 (SDK 28)
Plugin Version: 0.2.0
React Native Version: 0.59.5

Stack Trace:

java.lang.IllegalStateException: 
  at android.media.AudioRecord.startRecording (AudioRecord.java:1026)
  at com.goodatlas.audiorecord.RNAudioRecordModule.start (RNAudioRecordModule.java:94)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.facebook.react.bridge.JavaMethodWrapper.invoke (JavaMethodWrapper.java:372)
  at com.facebook.react.bridge.JavaModuleWrapper.invoke (JavaModuleWrapper.java:158)
  at com.facebook.react.bridge.queue.NativeRunnable.run (Native Method)
  at android.os.Handler.handleCallback (Handler.java:907)
  at android.os.Handler.dispatchMessage (Handler.java:105)
  at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage (MessageQueueThreadHandler.java:29)
  at android.os.Looper.loop (Looper.java:216)
  at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run (MessageQueueThreadImpl.java:232)
  at java.lang.Thread.run (Thread.java:784)```

Can I change file recorder wav file path ?

let audioFile = await AudioRecord.stop();

When I print audioFile value, I got path as below:

"data/user/0/com.chatboatsample/files/test.wav"

Can I change this path ? I want to store this file in root.

Not able to fetch recorded audio file

After stop Recording i'm not able to get base64 audio chanks.
AudioRecord.on('data', data => {
// base64-encoded audio data chunks
});
Above function return error " Sending data with no listener registered".
Can you please help.

How could I use chunks data to stream to server?

I have played around and stuck with streaming base64 chunk to server. I want to use this for google speech to text. Is there any document to archive this? Thanks for your help!

const audioPieces = [];
AudioRecord.on('data', data => {
   // base64-encoded audio data chunks
   audioPieces.push(Buffer.from(data, 'base64'));
});

function stopRecording() {
  console.log('stopRecording -> onStop', onStop);
  clearTimeout(recorderTimer);

  const audioFile = await AudioRecord.stop();
  const base64Data = Buffer.concat(audioPieces).toString('base64');
  sendBase64ToServer(base64Data)
  
  console.log('audioFile', audioFile);
}

Here is server code

const base64Data = base64DataFromClient
const defaultSTTConfig = {
  encoding: 'LINEAR16',
  sampleRateHertz: 16000,
  languageCode: 'en-US',
};
 const client = new speech.SpeechClient();

  const config = {
    ...defaultSTTConfig,
  };

  const request = {
    config,
    interimResults: false, // If you want interim results, set this to true
  };

  // Create a recognize stream
  const recognizeStream = client
    .streamingRecognize(request)
    .on('error', console.error)
    .on('data', (data) => {
      console.log('getTranscriptionFromFakeStream -> data', data);
      process.stdout.write(
        data.results[0] && data.results[0].alternatives[0]
          ? `Transcription: ${data.results[0].alternatives[0].transcript}\n`
          : '\n\nReached transcription time limit, press Ctrl+C\n',
      );
    });
  const buffer = Buffer.from(base64Data, 'base64');
  const readableStream = Readable.from([buffer]);

  readableStream.pipe(recognizeStream);

use with expo

Can i use this with Expo ?
The native expo Audio API doesnt support streaming..

error Linking "react-native-audio-record" failed.

react-native link react-native-audio-record does not seem to work. Getting the following error. please Help.
error Linking "react-native-audio-record" failed.
Error: ENOENT: no such file or directory, open 'C:\Users\user\Documents\front-end\ios\newproject.xcodeproj\project.pbxproj'

How to change the destination location?

By default, the library saves the audio file (.wav) to /data/user/0/com.new_recorder/files/

Is there a way to change the destination location? if so, how?

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.