Giter VIP home page Giter VIP logo

react-native-android-speech's Introduction

React Native Android Text To Speech

A react native android wrapper for Text To speech

Purpose

Currently , React Native doesn't have inbuilt support for TextToSpeech library for Android.

But with help of exposing module in react-native , this wrapper will solve the problem for TTS.

Setup

  • Install Module
npm install --save react-native-android-speech
  • android/settings.gradle
...
include ':react-native-android-speech'
project(':react-native-android-speech').projectDir = new File(settingsDir, '../node_modules/react-native-android-speech')
  • android/app/build.gradle
dependencies {
	...
	compile project(':react-native-android-speech')
}
  • for React Native Version >= 0.29, register module (in android/app/src/main/java/com/[app name]/MainApplication.java)
...
import com.mihir.react.tts.*; // Import package

public class MainApplication extends Application implements ReactApplication {
	...
	
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          ...,
          new RCTTextToSpeechModule()
      );
    }
}
  • for React Native Version < 0.29, register module (in android/app/src/main/java/com/[app name]/MainActivity.java)
...
import com.mihir.react.tts.*; // Import package

public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
	...
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .addPackage(new RCTTextToSpeechModule())           // Add any extra modules here
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        mReactRootView.startReactApplication(mReactInstanceManager, "YourProject", null);

        setContentView(mReactRootView);
    }
}

Usage

Currently there following functionality available. All below functions return Promise , with proper error codes.

  • getLocales
  • checkLanguageAvailability(language)
  • downloadTTSVoice()
  • speak(args)
  • isSpeaking
  • shutDown
  • stop

Importing module

var tts = require('react-native-android-speech')

getLocales()

Returns all available langauges from TTS make sure that exists in device also.

Example

tts.getLocales().then(locales=>{
    console.log(locales)
});

checkLanguageAvailability(language)

returns whether a language is available on the device TTS engine

Example

tts.checkLanguageAvailability('ko').then(result => {
    console.log('TTS voice availability for Korean is '+result);
});

downloadTTSVoice()

opens the TTS download page on the device

Example

tts.checkLanguageAvailability('ko').then(result => {
    if (!result) {
        downloadTTSVoice();
    }
});

speak()

Example

tts.speak({
    text:'Please provide some text to speak.', // Mandatory
    pitch:1.5, // Optional Parameter to set the pitch of Speech,
    forceStop : false , //  Optional Parameter if true , it will stop TTS if it is already in process
    language : 'en', // Optional Paramenter Default is en you can provide any supported lang by TTS
    country : 'US' // Optional Paramenter Default is null, it provoques that system selects its default
}).then(isSpeaking=>{
    //Success Callback
    console.log(isSpeaking);
}).catch(error=>{
    //Errror Callback
    console.log(error)
});

isSpeaking()

This method will help to figure out whether TTS engine is currently speaking or not.

Example

tts.isSpeaking()
.then(isSpeaking=>{
    //Callback
    console.log(isSpeaking);
})
.catch(error=>{
    //if it fails 
    console.log(error)
});

Stop()

Stop currently processing speech. Return True/False

Example

tts.shutDown()
.then(isStopped=>{
    console.log(isStopped);
})
.catch(error=>{
    console.log(error);
});

shutDown()

Shutdown TTS Engine

Example

tts.shutDown()
.then(shutDown=>{
    //Callback 
    console.log(shutDown);
})
.catch(error=>{
    console.log(error)
});

Changes

PR's are welcome

Todo

  • providing UternceId and callback
  • Differnt Voices
  • Custome Engines
  • Support Speech To Text

LICENSE

MIT

react-native-android-speech's People

Contributors

mihirsoni avatar rbermudezg avatar slycoder avatar vincenzoiacovone avatar yjlim5 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

Watchers

 avatar  avatar  avatar  avatar

react-native-android-speech's Issues

Error when building

Hi, I've ran through the install instructions but get the following errors when running:

C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:7: error: cannot find symbol
public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
                                  ^
  symbol: class Activity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:7: error: cannot find symbol
public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
                                                      ^
  symbol: class DefaultHardwareBackBtnHandler
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:9: error: cannot find symbol
    protected void onCreate(Bundle savedInstanceState) {
                            ^
  symbol:   class Bundle
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:8: error: method does not override or implement a method
from a supertype
    @Override
    ^
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:10: error: cannot find symbol
        super.onCreate(savedInstanceState);
        ^
  symbol:   variable super
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:11: error: cannot find symbol
        mReactRootView = new ReactRootView(this);
        ^
  symbol:   variable mReactRootView
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:11: error: cannot find symbol
        mReactRootView = new ReactRootView(this);
                             ^
  symbol:   class ReactRootView
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:13: error: cannot find symbol
        mReactInstanceManager = ReactInstanceManager.builder()
        ^
  symbol:   variable mReactInstanceManager
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:20: error: cannot find symbol
                .setInitialLifecycleState(LifecycleState.RESUMED)
                                          ^
  symbol:   variable LifecycleState
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:17: error: cannot find symbol
                .addPackage(new MainReactPackage())
                                ^
  symbol:   class MainReactPackage
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:14: error: cannot find symbol
                .setApplication(getApplication())
                                ^
  symbol:   method getApplication()
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:13: error: cannot find symbol
        mReactInstanceManager = ReactInstanceManager.builder()
                                ^
  symbol:   variable ReactInstanceManager
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:23: error: cannot find symbol
        mReactRootView.startReactApplication(mReactInstanceManager, "PT", null);
                                             ^
  symbol:   variable mReactInstanceManager
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:23: error: cannot find symbol
        mReactRootView.startReactApplication(mReactInstanceManager, "PT", null);
        ^
  symbol:   variable mReactRootView
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:25: error: cannot find symbol
        setContentView(mReactRootView);
                       ^
  symbol:   variable mReactRootView
  location: class MainActivity
C:\Railton\Android\PT\android\app\src\main\java\com\pt\MainActivity.java:31: error: method does not override or implement a method
 from a supertype
    @Override
    ^
16 errors
:app:compileDebugJavaWithJavac FAILED

The contents of MainActivity.java is as follows:

package com.pt;

import com.facebook.react.ReactActivity;
import com.mihir.react.tts.*;

//public class MainActivity extends ReactActivity {
public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .addPackage(new RCTTextToSpeechModule())           
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        mReactRootView.startReactApplication(mReactInstanceManager, "PT", null);

        setContentView(mReactRootView);
    }
    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "PT";
    }
}

the text-to-speech is not working after built

I can successfully built your project, however the text-to-speech is not working, I can't hear the audio after clicked on "button" text, the apk file is installed in android phone.
Here is my index.android.js

` import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
TouchableHighlight,
TouchableNativeFeedback
} from 'react-native';

var tts = require('react-native-android-speech')

function buttonClicked () {
    tts.speak({
        text:'Please provide some text to speak.', // Mandatory
        pitch:1.5, // Optional Parameter to set the pitch of Speech,
        forceStop : false , //  Optional Parameter if true , it will stop TTS if it is already in process
        language : 'en' // Optional Paramenter Default is en you can provide any supported lang by TTS
    }).then(isSpeaking=>{
        //Success Callback
        console.log(isSpeaking);
    }).catch(error=>{
        //Errror Callback
        console.log(error)
    });

     setTimeout(function(){ alert("finished here"); }, 3000);

}
class mysound extends Component {

  render() {
    var TouchableElement = TouchableHighlight;
    if (Platform.OS === 'android') {
        TouchableElement = TouchableNativeFeedback;
    }
    return (
      <View style={styles.container}>
          <Text style={styles.welcome}>
            Tap me as fast as you can!
          </Text>

          <TouchableElement
            onPress={buttonClicked}>
            <View>
              <Text>Button!</Text>
            </View>
          </TouchableElement>
  </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
AppRegistry.registerComponent('mysound', () => mysound);

`
Can you please tell me why this is not working ? I have downloaded your code before one month and since then I have been working on this.

problem on building react-native project

As you suggested I have done following in MainActivity.java

package com.mysound;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "mysound";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .addPackage(new RCTTextToSpeechModule())           // Add any extra modules here
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        mReactRootView.startReactApplication(mReactInstanceManager, "YourProject", null);

        setContentView(mReactRootView);
    }  
}

After run the react-native run-android command, I got following error

error3

How to fix this problem?

Different voices options

Hi, guys. I am so happy that you had created this module. Thank you for that.
But I would like to add some other different voices options, like Homer Simpson or some Monkey or a Robot or something funny. Is it possible? Thanks

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.