Giter VIP home page Giter VIP logo

voice's Introduction

CircleCI branch npm

React Native Voice

A speech-to-text library for React Native.

chat on Discord
yarn add @react-native-voice/voice

# or

npm i @react-native-voice/voice --save

Link the iOS package

npx pod-install

Table of contents

Linking

Manually or automatically link the NativeModule

react-native link @react-native-voice/voice

Manually Link Android

  • In android/setting.gradle
...
include ':@react-native-voice_voice', ':app'
project(':@react-native-voice_voice').projectDir = new File(rootProject.projectDir, '../node_modules/@react-native-voice/voice/android')
  • In android/app/build.gradle
...
dependencies {
    ...
    compile project(':@react-native-voice_voice')
}
  • In MainApplication.java
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactPackage;
...
import com.wenkesj.voice.VoicePackage; // <------ Add this!
...

public class MainActivity extends Activity implements ReactApplication {
...
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new VoicePackage() // <------ Add this!
        );
    }
}

Manually Link iOS

  • Drag the Voice.xcodeproj from the @react-native-voice/voice/ios folder to the Libraries group on Xcode in your poject. Manual linking

  • Click on your main project file (the one that represents the .xcodeproj) select Build Phases and drag the static library, lib.Voice.a, from the Libraries/Voice.xcodeproj/Products folder to Link Binary With Libraries

Prebuild Plugin

This package cannot be used in the "Expo Go" app because it requires custom native code.

After installing this npm package, add the config plugin to the plugins array of your app.json or app.config.js:

{
  "expo": {
    "plugins": ["@react-native-voice/voice"]
  }
}

Next, rebuild your app as described in the "Adding custom native code" guide.

Props

The plugin provides props for extra customization. Every time you change the props or plugins, you'll need to rebuild (and prebuild) the native app. If no extra properties are added, defaults will be used.

  • speechRecognition (string | false): Sets the message for the NSSpeechRecognitionUsageDescription key in the Info.plist message. When undefined, a default permission message will be used. When false, the permission will be skipped.
  • microphone (string | false): Sets the message for the NSMicrophoneUsageDescription key in the Info.plist. When undefined, a default permission message will be used. When false, the android.permission.RECORD_AUDIO will not be added to the AndroidManifest.xml and the iOS permission will be skipped.

Example

{
  "plugins": [
    [
      "@react-native-voice/voice",
      {
        "microphonePermission": "CUSTOM: Allow $(PRODUCT_NAME) to access the microphone",
        "speechRecognitionPermission": "CUSTOM: Allow $(PRODUCT_NAME) to securely recognize user speech"
      }
    ]
  ]
}

Usage

Full example for Android and iOS.

Example

import Voice from '@react-native-voice/voice';
import React, {Component} from 'react';

class VoiceTest extends Component {
  constructor(props) {
    Voice.onSpeechStart = this.onSpeechStartHandler.bind(this);
    Voice.onSpeechEnd = this.onSpeechEndHandler.bind(this);
    Voice.onSpeechResults = this.onSpeechResultsHandler.bind(this);
  }
  onStartButtonPress(e){
    Voice.start('en-US');
  }
  ...
}

API

Static access to the Voice API.

All methods now return a new Promise for async/await compatibility.

Method Name Description Platform
Voice.isAvailable() Checks whether a speech recognition service is available on the system. Android, iOS
Voice.start(locale) Starts listening for speech for a specific locale. Returns null if no error occurs. Android, iOS
Voice.stop() Stops listening for speech. Returns null if no error occurs. Android, iOS
Voice.cancel() Cancels the speech recognition. Returns null if no error occurs. Android, iOS
Voice.destroy() Destroys the current SpeechRecognizer instance. Returns null if no error occurs. Android, iOS
Voice.removeAllListeners() Cleans/nullifies overridden Voice static methods. Android, iOS
Voice.isRecognizing() Return if the SpeechRecognizer is recognizing. Android, iOS
Voice.getSpeechRecognitionServices() Returns a list of the speech recognition engines available on the device. (Example: ['com.google.android.googlequicksearchbox'] if Google is the only one available.) Android

Events

Callbacks that are invoked when a native event emitted.

Event Name Description Event Platform
Voice.onSpeechStart(event) Invoked when .start() is called without error. { error: false } Android, iOS
Voice.onSpeechRecognized(event) Invoked when speech is recognized. { error: false } Android, iOS
Voice.onSpeechEnd(event) Invoked when SpeechRecognizer stops recognition. { error: false } Android, iOS
Voice.onSpeechError(event) Invoked when an error occurs. { error: Description of error as string } Android, iOS
Voice.onSpeechResults(event) Invoked when SpeechRecognizer is finished recognizing. { value: [..., 'Speech recognized'] } Android, iOS
Voice.onSpeechPartialResults(event) Invoked when any results are computed. { value: [..., 'Partial speech recognized'] } Android, iOS
Voice.onSpeechVolumeChanged(event) Invoked when pitch that is recognized changed. { value: pitch in dB } Android

Permissions

Arguably the most important part.

Android

While the included VoiceTest app works without explicit permissions checks and requests, it may be necessary to add a permission request for RECORD_AUDIO for some configurations. Since Android M (6.0), user need to grant permission at runtime (and not during app installation). By default, calling the startSpeech method will invoke RECORD AUDIO permission popup to the user. This can be disabled by passing REQUEST_PERMISSIONS_AUTO: true in the options argument.

If you're running an ejected expo/expokit app, you may run into issues with permissions on Android and get the following error host.exp.exponent.MainActivity cannot be cast to com.facebook.react.ReactActivity startSpeech. This can be resolved by prompting for permssion using the expo-permission package before starting recognition.

import { Permissions } from "expo";
async componentDidMount() {
	const { status, expires, permissions } = await Permissions.askAsync(
		Permissions.AUDIO_RECORDING
	);
	if (status !== "granted") {
		//Permissions not granted. Don't show the start recording button because it will cause problems if it's pressed.
		this.setState({showRecordButton: false});
	} else {
		this.setState({showRecordButton: true});
	}
}

Notes on Android

Even after all the permissions are correct in Android, there is one last thing to make sure this libray is working fine on Android. Please make sure the device has Google Speech Recognizing Engine such as com.google.android.googlequicksearchbox by calling Voice.getSpeechRecognitionServices(). Since Android phones can be configured with so many options, even if a device has googlequicksearchbox engine, it could be configured to use other services. You can check which serivce is used for Voice Assistive App in following steps for most Android phones:

Settings > App Management > Default App > Assistive App and Voice Input > Assistive App

Above flow can vary depending on the Android models and manufactures. For Huawei phones, there might be a chance that the device cannot install Google Services.

How can I get com.google.android.googlequicksearchbox in the device?

Please ask users to install Google Search App.

iOS

Need to include permissions for NSMicrophoneUsageDescription and NSSpeechRecognitionUsageDescription inside Info.plist for iOS. See the included VoiceTest for how to handle these cases.

<dict>
  ...
  <key>NSMicrophoneUsageDescription</key>
  <string>Description of why you require the use of the microphone</string>
  <key>NSSpeechRecognitionUsageDescription</key>
  <string>Description of why you require the use of the speech recognition</string>
  ...
</dict>

Please see the documentation provided by ReactNative for this: PermissionsAndroid

Contributors

  • @asafron
  • @BrendanFDMoore
  • @brudny
  • @chitezh
  • @ifsnow
  • @jamsch
  • @misino
  • @Noitidart
  • @ohtangza & @hayanmind
  • @rudiedev6
  • @tdonia
  • @wenkesj

voice's People

Contributors

anfriis avatar brendanfdmoore avatar brudny avatar chitezh avatar danieloi avatar dependabot[bot] avatar elledienne avatar evanbacon avatar fixerteam avatar harrolee avatar ifsnow avatar jamsch avatar lucasbento avatar lucianomlima avatar luism3861 avatar maxmatthews avatar mdboop avatar misino avatar naturalclar avatar neusoft-technology-solutions avatar noitidart avatar ohtangza avatar rudiedev6 avatar safaiyeh avatar semantic-release-bot avatar sibelius avatar suhairzain avatar tdonia avatar wenkesj avatar yujif 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  avatar  avatar  avatar  avatar  avatar  avatar

voice's Issues

Offline Speech Recognition

Hi,
I read that this react-native-voice provides Online and Offline Support.

Does this mean that it can work offline?

I tested it and it keeps popping network error when I try offline on my AVD.

Any thoughts?

Thanks

offline mode

Did React-native-voice is compatible with Google offline speech recognition?

Error when i try to cancel or stop recognize

Start recognize work fine and destroy, but if i try cancel on stop i get error:
216/The operation couldn’t be completed. (kAFAssistantErrorDomain error 216.)

System ios 11.2

Minimum Android version?

Hi there, thanks for this awesome lib. What is the minimum android version? RN supports down to 4.1.

Not recognize for iOS

This lib works well in Android.
As my debug, Voice.onSpeechStart(event) is triggered but Voice.onSpeechRecognized(event) is not called.

I'm using:
react-native-voice: 0.1.12
react: 16.0.0-alpha.12
react-native: 0.46.4

Regards!

iOS only saves the first word of the phrase

Anyone know why it would only capture the first word? It is working fine on Android this issue is only occurring on iOS. I am not sure if it is only returning the first word, or is stopping listening after the first word is recognized.

Does this convert speech to text in real-time?

Hello! Does this library recognize speech and converts it to text in real-time? I mean when I say "one" and then pause for 1 second and then say "two". Will those two words trigger two separate callbacks?

There are at least 2 events that potentially does what I want to accomplish:

  • onSpeechRecognized
  • onSpeechPartialResults

Which one of these gets executed every time a single word is recognized? Thanks!

VoiceTest - No Working

I have built the VoiceTest project successfully.
I have run on ios-simulator.
But the app does not recognize my voice, so timeout error was issued.
Help me! Thanks.

Bug: Android issue Voice issue when navigate goBack()

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Above was the issue I got when I try to navigate::goBack and play the mic button again. I'm not sure why the states we define on contruct is having an issue it already bind functions, is there missing function on this list? (I copied it on the example you provided)

    Voice.onSpeechStart = this.onSpeechStart.bind(this);
    Voice.onSpeechRecognized = this.onSpeechRecognized.bind(this);
    Voice.onSpeechEnd = this.onSpeechEnd.bind(this);
    Voice.onSpeechError = this.onSpeechError.bind(this);
    Voice.onSpeechResults = this.onSpeechResults.bind(this);
    Voice.onSpeechPartialResults = this.onSpeechPartialResults.bind(this);
    Voice.onSpeechVolumeChanged = this.onSpeechVolumeChanged.bind(this);

Could you please guide me if you have come across this issue?

Thanks,

ios OK, but android Error Service not registered:

i have run ios success, but android can not start, the error is:

ExceptionsManager.js:73 Error: Service not registered: android.speech.SpeechRecognizer$Connection@8d30714
    at callback (index.js:61)
    at MessageQueue.__invokeCallback (MessageQueue.js:354)
    at MessageQueue.js:129
    at MessageQueue.__guard (MessageQueue.js:269)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (MessageQueue.js:128)
    at t (RNDebuggerWorker.js:1)

[iOS] Crash on com.apple.coreaudio.avfaudio: required condition is false: IsFormatSampleRateAndChannelCountValid(format)

Hi, I'm getting an error while starting up speech recognition on an iPad Air 2. Not sure what is causing the issue.

Environment

"device": {
    "family": "iOS",
    "arch": "arm64",
    "storage_size": 63989493760,
    "free_memory": 51675136,
    "memory_size": 2084569088,
    "boot_time": "2017-11-13T07:29:50Z",
    "model": "iPad5,4",
    "usable_memory": 1687126016,
    "type": "device"
},

"os": {
    "rooted": false,
    "kernel_version": "Darwin Kernel Version 17.2.0: Fri Sep 29 18:14:52 PDT 2017; root:xnu-4570.20.62~4/RELEASE_ARM64_T7001",
    "version": "11.1.1",
    "build": "15B150",
    "type": "os",
    "name": "iOS"
}

Exception

Application threw exception com.apple.coreaudio.avfaudio: required condition is false: IsFormatSampleRateAndChannelCountValid(format)

Originated at or in a subcall of folly::Expected<long long, folly::ConversionCode> folly::detail::str_to_integral<long long>(folly::Range<char const*>*)

VoiceModule.startSpeech(): Support for setting intent parameters

Any possibility of adding support for setting intent parameters like:
• EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS
• EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS
• EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS

...in VoiceModule.startSpeech() in order to control things such as the length of the speech capture?

Terminating with uncaught exception of type NSException

Just tried running the example app and when calling the Stop/Cancel or Destroy methods, I'm getting:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[1]'

libc++abi.dylib: terminating with uncaught exception of type NSException
in
React/Executors/RCTJSCExecutor.mm
on line:

while (kCFRunLoopRunStopped != CFRunLoopRunInMode(kCFRunLoopDefaultMode, ((NSDate *)[NSDate distantFuture]).timeIntervalSinceReferenceDate, NO)) {

Has anyone else come across this bug?

Crash occasionally while keep starting and stopping

and i got error massage in xcode console
[avae] AVAEInternal.h:69:_AVAE_Check: required condition is false: [AVAEGraphNode.mm:804:CreateRecordingTap: (nullptr == Tap())]
*** Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: nullptr == Tap()'
*** First throw call stack:
(0x1841dfd38 0x1836f4528 0x1841dfc0c 0x1898ed634 0x1898ecc7c 0x18992ec18 0x189919064 0x189991a78 0x18998238c 0x1050b9ca8 0x1050bbed0 0x10587549c 0x10587545c 0x10588156c 0x105886b54 0x105886880 0x183e0b130 0x183e0ac30)
libc++abi.dylib: terminating with uncaught exception of type NSException

anyone have solution for this? thanks

i am using real device, iphone 7plus, ios 11 to test.

Providing audio file as input to speech to text

Can we provide a short audio file (.mp3) as an input to react-native-voice and get the corresponding text?
Since it does not allow to save the audio file, we need to use the audio file later as well.

Limit possibilities dictionary (ie: numbes only)

I have two apps that use voice. The first one the users are saying one of 300 items. Is it possible to limit the voice recognition to only return closest elements to ones in an array?

In another application, the users are saying a single number, or multiple numbers. Anyway to limit to just numbers?

Play Sound

Awesome module! Is it possible to play a sound or speak text? If I use this module together with react-native-audio-toolkit it crashes(iOS) when I want to play a sound in my App.

Android works fine, iOS doesn't

Hi there!

First, congratulations this library looks really cool. Good work!

I have problems in iOS though.

  1. The simulator crashes on the demo when tapping in the Start Button and closes
  2. The device has a more weird error:

"Failed to load bundle" with error (Error reading bundle) ... main.jsbundle(null)

Any ideas?

Fallback for ios versions below 10

Hello, thanks for this handy library, i there a way to provide a fallback error when using this library for ios 8, 9 instead of crashing due SO support? this way we can use this library for ios +10 but also we can include it optionally for lower versions.

Continuously listening to user input

It seems that the voice detecting function will terminate after starting detection a few seconds. Is there exist a way to keep listening to user input?

Thanks!

Voice.stop() doesn't work as expected

IOS,
react-native: 0.48.2,
react-native-voice: 0.2.1,

Hi

So basically when i try to call Voice.stop() without any recognized voice i receive Error (203/Retry).

But if i have at least 1 recognized word Voice.stop() works fine

4/error from server

I am using Android 6 for testing. However after I do Voice.start() and it returns undefined I then speak and it trigger onSpeechError with error being { message: "4/error from server" }.

May you please advise.

Here is my component:

// @flow

import React, { PureComponent } from 'react'
import { Button, PermissionsAndroid, Text, View } from 'react-native'
import Voice from 'react-native-voice'

import styles from './styles'

class VoiceButton extends PureComponent {
    state = {
        isRecording: false,
        partial: '',
        result: ''
    }

    componentDidUpdate(propsOld, stateOld) {
        const { isRecording } = this.state;
        const { isRecording:isRecordingOld } = stateOld;

        if (isRecording !== isRecordingOld) {
            if (isRecording) this.voiceStart()
            else this.voiceStop();
        }
    }
    componentWillUnmount() {
        this.voiceDestroy();
    }
    render() {
        const { partial, result, isRecording } = this.state;
        return (
            <View style={styles.container}>
                <View>
                    <Text>{isRecording ? 'Listening...' : 'Press and hold button then speak'}</Text>
                </View>
                <Button title="Record" onPress={this.handlePress} />
                <View>
                    <Text>PARTIAL RESULTS</Text>
                    <Text>{partial}</Text>
                </View>
                <View>
                    <Text>RESULT</Text>
                    <Text>{result}</Text>
                </View>
            </View>
        )
    }

    handlePress = () => this.setState(({ isRecording }) => ({ isRecording:!isRecording }))

    voiceStart = async () => {
        this.setState(() => ({ result:'', partial:'' }));
        console.log('Voice.isAvailable():', await Voice.isAvailable());

        try {
            const didGrant = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, { title:'Microphone Permission', message:'Enter the Gunbook needs access to your microphone so you can search with voice.' });
            console.log('didGrant:', didGrant);
            if (didGrant !== PermissionsAndroid.RESULTS.GRANTED) {
                console.log('you denied permission');
                return;
            }
        } catch(err) {
            console.error('failed getting permission, err:', err.message);
            return;
        }

        // Voice.onSpeechStart = this.handleSpeechStart;
        // Voice.onSpeechRecognized = this.handleSpeechRecognized;
        // Voice.onSpeechEnd = this.handleSpeechEnd;
        Voice.onSpeechError = this.handleSpeechError;
        Voice.onSpeechResults = this.handleSpeechResults;
        Voice.onSpeechPartialResults = this.handleSpeechPartialResults;
        // Voice.onSpeechVolumeChanged = this.handleSpeechVolumeChanged;
        try {
            const started = await Voice.start('en');
            console.log('started:', started);
        } catch(err) {
            console.error('Failed to start, err:', err);
        }
    }
    voiceStop = async () => {
        try {
            const stopped = await Voice.stop();
            console.log('stopped:', stopped);
        } catch(err) {
            console.error('Failed to stop, err:', err);
        }
    }
    voiceCancel = async () => {
        try {
            await Voice.cancel();
        } catch(err) {
            console.error('Failed to cancel, err:', err);
        }
    }
    voiceDestroy = async () => {
        try {
            const destroyed = await Voice.destroy();
            console.log('destroyed:', destroyed);
            Voice.removeAllListeners(destroyed);
        } catch(err) {
            console.error('Failed to destroy, err:', err);
        }

    }

    // handleSpeechStart =
    // handleSpeechRecognized =
    // handleSpeechEnd =
    handleSpeechError = ({ error }) => console.error('speech recording error:', error);
    handleSpeechResults = ({ value }) => this.setState(() => ({ result:value }));
    handleSpeechPartialResults = ({ value }) => this.setState(() => ({ partial:value }));
}

export default VoiceButton

Does this module work in latest react-native 0.41.2

Hi,

First of all thanks for sharing this plugin. I am using following react-native, Does your module work in these versions.

react-native-cli: 2.0
react-native: 0.41.2

If NO how do I run your plugin in mentioned react-native?

Issue "Cannot read property Bind of undefine"

Hi,

I'm having this issue about this module. This code

    Voice.onSpeechStart = this.onSpeechStart.bind(this);
    Voice.onSpeechRecognized = this.onSpeechRecognized.bind(this);
    Voice.onSpeechEnd = this.onSpeechEnd.bind(this);
    Voice.onSpeechError = this.onSpeechError.bind(this);
    Voice.onSpeechResults = this.onSpeechResults.bind(this);
    Voice.onSpeechPartialResults = this.onSpeechPartialResults.bind(this);
    Voice.onSpeechVolumeChanged = this.onSpeechVolumeChanged.bind(this);

is causing the bind issue on the constructor(props) is there a way to fix this issue?

thanks,

FAILURE: Build failed with an exception.

Hi,
I tried to install this package but something wrong append when I build :
I've link the package with :
react-native link react-native-voice
and i've update the gradle settings & the gardle build correctly

and this build return :

Execution failed for task ':app:processDebugResources'.
> Error: more than one library with package name 'com.wenkesj.voice'

What should i do to fix that ?
Tanks

Can you use it with other language than English?

Hello, I tried to use react-native-voice and it works perfectly. But now I would like to use it with french. I replace en-US with fr-FR in Voice.start('en-US') but it doesn't works at all (except if I speak english).

example from project is not working

I have tried to run your example from this project but it does not work. It shows below error.

image

What I have done wrong, can you please give some light on this?

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.