I have a FrameLayout with two ImageButtons (Play, Stop). By default
Play button is VISIBLE, Stop button is GONE
Clicking the Play starts the TTS Engine which reads the text. On Completion of reading the text, I want to set the Visibility of
Play to GONE, Stop to VISIBLE
Should I use the UtteranceProgressListener to serve the purpose? If not,
How can I perform the above action?
What is the purpose of UtteranceProgressListener?
Did you perhaps mean that:
reading starts -> Play is gone and Stop is visible
reading ends -> Play is visible, Stop is gone
Anyway, the purpose of UtteranceProgressListener is exactly what you are describing. It's used to monitor the progress of the speech synthesis.
You can add an "utterance id" (here "helloText") to any text that is spoken out:
tts.speak("Hello Stack Overflow!", TextToSpeech.QUEUE_ADD, "helloText");
But that's not really necessary in your case, so the last parameter can be null:
tts.speak("Hello Stack Overflow!", TextToSpeech.QUEUE_ADD, null);
The UtteranceProgressListener should be added before calling speak(). You could do that for example in the TTS initialization callback onInit() if the TTS status is TextToSpeech.SUCCESS.
It can be a separate class or just an anonymous inner class:
speech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
// Speaking started.
}
#Override
public void onDone(String utteranceId) {
// Speaking stopped.
}
}
#Override
public void onError(String utteranceId) {
// There was an error.
}
});
The onStart() method is triggered when speaking starts (soon after calling speak()) so that's one possible place to switch the visible button. For example the Play button could be switched to a Stop button.
The onDone() method is triggered when speaking is finished and it's another possible place to switch the visible button. For example the Stop button could be switched to a Play button.
And as you can see the "utterance id" is available in both methods if you provided a one in the speak() method call. It would be useful if you needed to know exactly which text is being spoken/finished being spoken/failed with an error.
UtteranceProgressListener can be used to identify when the TTS is completed. Try this following code which shows a toast after TTS completed.
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{
private boolean initialized;
private String queuedText;
private String TAG = "TTS";
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this /* context */, this /* listener */);
tts.setOnUtteranceProgressListener(mProgressListener);
speak("hello world");
}
public void speak(String text) {
if (!initialized) {
queuedText = text;
return;
}
queuedText = null;
setTtsListener(); // no longer creates a new UtteranceProgressListener each time
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
tts.speak(text, TextToSpeech.QUEUE_ADD, map);
}
private void setTtsListener() {
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
initialized = true;
tts.setLanguage(Locale.ENGLISH);
if (queuedText != null) {
speak(queuedText);
}
}
}
private abstract class runnable implements Runnable {
}
private UtteranceProgressListener mProgressListener = new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
} // Do nothing
#Override
public void onError(String utteranceId) {
} // Do nothing.
#Override
public void onDone(String utteranceId) {
new Thread()
{
public void run()
{
MainActivity.this.runOnUiThread(new runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), "TTS Completed", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
};
}
Related
In Android TextToSpeech, How come we know either Speech is finished. I want to change icon after speech finished. I declared tts.speak() in Button Onclick Listener. i used thread postdelayed handler to change icon after some time. but the text to read changes different at different times.It didnt worked out. CheckThemestart(),ChangeThemeStop() are functions to change the icon.
i declared the following in OnCreate() :
tts = new TextToSpeech(getContext(), new
TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.UK);
tts.speak("",TextToSpeech.QUEUE_FLUSH,null);
}
Button-onClickListener :
if (!tts.isSpeaking()) {
CheckThemeStart();
tts.speak(plainText, TextToSpeech.QUEUE_FLUSH, null);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//change icon after spoken
CheckThemeStop();
}
}, 15000);
} else {
CheckThemeStop();
tts.stop();
}
You can register UtteranceProgressListener for tts start and end times and error handling.
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
}
#Override
public void onDone(String s) {
}
#Override
public void onError(String s) {
}
});
If we declare a hasmap parameter with unique string ID and pass that id to compare utterence id if matches it execute what you declare inside onUtterenceCompletedListener().
The following is code snippet.
HashMap<String,String> params=new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"SpeakID");
tts.speak(plainText, TextToSpeech.QUEUE_FLUSH,params);
tts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String utteranceId) {
if(utteranceId.equals("SpeakID"))
{
CheckThemeStop();
}
}
});
I've put together an activity that uses the TTS API and code I've used in another project for the same purpose. However, TTS fails to operate and the activity fails to launch all together. I've studied my code and cannot decipher where the problem is. The code matches my other project's code exactly, and the code in the other project works as expected. The log cat data is hard to understand, so hopefully someone in this community can help me find the problem. I think it may be an Android Studio issue. The other project is installed within Eclipse Luna. It's got to be the TTS code because the activity in question was launching just fine before I added the TTS code. I've attached my code and the log cat info.
ADDITIONAL INFO: Perhaps it's the behavior I am trying to implement. I am attempting to send a saved string to the TTS engine upon the loading of the activity into view, using a timer to launch TTS 1 second after the view initializes. I'm not sure, however, if I can launch an instance of TTS without a button press to execute it. My other project, which works, calls the TTS engine on the click of a button...???
public class InfoGreetView extends ActionBarActivity implements TextToSpeech.OnInitListener, TextToSpeech.OnUtteranceCompletedListener {
TextView infoGreetPrompt = (TextView) findViewById(R.id.infoGreetPrompt);
TextToSpeech textToSpeech;
Timer timer = new Timer();
Timer timer2 = new Timer();
TimerTask timerTask;
TimerTask timerTask2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_greet_view);
textToSpeech = new TextToSpeech(this,this);
timerTask = new TimerTask() {
#Override
public void run() {
Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);
startPlayback();
}
};
timer.schedule(timerTask,1000);
}
#Override
public void onDestroy(){
if (textToSpeech != null){
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status){
if (status == TextToSpeech.SUCCESS){
int result = textToSpeech.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(getApplicationContext(), R.string.messagePlaybackInterrupted, Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), R.string.messagePlaybackInterrupted, Toast.LENGTH_LONG).show();
}
}
public void startPlayback(){
String infoGreetViewPrompt = infoGreetPrompt.getText().toString();
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "completed");
textToSpeech.speak(infoGreetViewPrompt, TextToSpeech.QUEUE_FLUSH, myHashRender);
}
#Override
public void onUtteranceCompleted(String utteranceId){
timerTask2 = new TimerTask() {
#Override
public void run() {
Intent displayGuestMessageView = new Intent(InfoGreetView.this, GuestMessageView.class);
startActivity(displayGuestMessageView);
}
};
timer2.schedule(timerTask2, 1000);
}
Hooray! I figured out what the issue was. First of all, my dependencies in Android Studio were not completed. I had to add the compile 'com.android.support:support-v4:20.0.0' jar; all I had in there was compile 'com.android.support:appcompat-v7:20.0.0'. I believe this is why TTS was not operating.
Second, I had tried to mimick Xcode's viewDidAppear method along with a timer so that TTS would begin when the view appeared, within onResume(). However, this was not working. The Log Cat said something about not binding to TTS. So, I threw my timer into onCreate() and instead of throwing my startPlayback() method separately from a call within my timer, I simply added the code within startPlayback() into my timer. Why? For some reason, the call wasn't happening. Here is my new and perfectly operating code!
public class InfoGreetView extends ActionBarActivity implements TextToSpeech.OnInitListener, TextToSpeech.OnUtteranceCompletedListener {
TextView infoGreetPrompt;
TextToSpeech textToSpeech;
ImageView attentionButton;
Timer timer = new Timer();
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_greet_view);
attentionButton = (ImageView) findViewById(R.id.attentionButton);
infoGreetPrompt = (TextView) findViewById(R.id.infoGreetPrompt);
textToSpeech = new TextToSpeech(this,this);
timerTask = new TimerTask() {
#Override
public void run() {
String text = infoGreetPrompt.getText().toString();
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "completed");
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, myHashRender);
}
};
timer.schedule(timerTask,500);
}
#Override
protected void onDestroy(){
super.onDestroy();
if (textToSpeech != null){
textToSpeech.stop();
textToSpeech.shutdown();
}
}
#Override
public void onInit(int status){
if (status == TextToSpeech.SUCCESS){
int result = textToSpeech.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(getApplicationContext(), R.string.languageNotSupported, Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), R.string.messagePlaybackInterrupted, Toast.LENGTH_LONG).show();
}
textToSpeech.setOnUtteranceCompletedListener(this);
}
#Override
public void onUtteranceCompleted(String utteranceId){
Intent displayGuestMessageView = new Intent(InfoGreetView.this, GuestMessageView.class);
startActivity(displayGuestMessageView);
}
}
Here is my code, I have a series of questions that will be asked by TTS and after every question speech recognizer will be invoked.My utterance listener is never being called.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech_recognizer);
tts = new TextToSpeech(this /* context */, this /* listener */);
}
//This is called after first time user clicks a button
private void processEnquiry() {
// TODO Auto-generated method stub
for(int i=0;i<EnquiryList.size();i++)
{
speak(EnquiryList.get(i).toString());
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
initialized = true;
tts.setLanguage(Locale.ENGLISH);
if (queuedText != null) {
speak(queuedText);
}
}
}
public void speak(String text) {
// If not yet initialized, queue up the text.
if (!initialized) {
queuedText = text;
return;
}
queuedText = null;
// Before speaking the current text, stop any ongoing speech.
//tts.stop();
// Speak the text.
setTtsListener();
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"MessageId");
tts.speak(text, TextToSpeech.QUEUE_ADD, map);
}
private void setTtsListener()
{
final SpeechRecognizer callWithResult = this;
int listenerResult = tts.setOnUtteranceProgressListener(new UtteranceProgressListener()
{
#Override
public void onDone(String utteranceId)
{
callWithResult.onDone(utteranceId);
}
#Override
public void onError(String utteranceId)
{
callWithResult.onError(utteranceId);
}
#Override
public void onStart(String utteranceId)
{
callWithResult.onStart(utteranceId);
}
});
if (listenerResult != TextToSpeech.SUCCESS)
{
Log.e(TAG, "failed to add utterance progress listener");
}
}
public void onDone(String utteranceId)
{
callSpeechRecognition();
}
public void onError(String utteranceId)
{
}
public void onStart(String utteranceId)
{
}
TextToSpeech.SUCCESS returns 0.
Here's a modified version of your script, where the onDone() method in the Utterance listener is called. I have eliminated many features that are not directly connected to the TTS playback, to create a barebones sample. If this works for you, then you can add back the other features one by one, testing that nothing breaks on the way.
import android.app.Activity;
import android.os.Bundle;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.view.View;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private SpeechRecognizer sr;
private boolean initialized;
private String queuedText;
private String TAG = "TTS";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech_recognizer);
tts = new TextToSpeech(this /* context */, this /* listener */);
tts.setOnUtteranceProgressListener(mProgressListener);
sr = SpeechRecognizer.createSpeechRecognizer(this); // added
}
// Modified for testing purposes
//This is called after first time user clicks a button
/*
private void processEnquiry() {
for (int i = 0; i < EnquiryList.size(); i++) {
speak(EnquiryList.get(i).toString());
}
}
*/
public void processEnquiry(View v) {
speak("Process enquiry");
}
// End of modification
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
initialized = true;
tts.setLanguage(Locale.ENGLISH);
if (queuedText != null) {
speak(queuedText);
}
}
}
public void speak(String text) {
// If not yet initialized, queue up the text.
if (!initialized) {
queuedText = text;
return;
}
queuedText = null;
// Before speaking the current text, stop any ongoing speech.
//tts.stop();
// Speak the text.
setTtsListener(); // no longer creates a new UtteranceProgressListener each time
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
tts.speak(text, TextToSpeech.QUEUE_ADD, map);
}
private void setTtsListener() {
// Method radically simplified; callWithResult is retained but not used here
final SpeechRecognizer callWithResult = sr; // was `this`
}
private UtteranceProgressListener mProgressListener = new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
} // Do nothing
#Override
public void onError(String utteranceId) {
} // Do nothing.
#Override
public void onDone(String utteranceId) {
callSpeechRecognition();
}
};
private void callSpeechRecognition() {
Log.d(TAG, "callSpeechRecognition() called");
}
}
I'm not sure exactly and not sure if this answer will help you, but I think you should not set UtteranceProgressListener every time you request TTS to speak, instead you should set the listener at onInit() once.
And note that the empty text will not be spoken so no callback will be invoked as well.
Though basically setting the listener after TTS initialization looks fine for me and works without problems on my Nexus5 and GalaxyS4, even if setting the listener every time I request TTS to speak, so there might be some device specific problems or some TTS engine specific problems.
Oops I forgot to mention that UtteranceProgressListener is available on API level 15 and above, so the listener will no be invoked on API level 14 and below.
I'm building an app in which there is tts part, in the main activity i'm creating an instance of tts like
public class Translator extends Activity implements OnClickListener{
TextToSpeech tts;
ArrayList<TTS.resultData> textsToBeSpoken = new ArrayList<TTS.resultData>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_translator);
initTTS();//calling to initialise tts;
}
}
and i'm calling the initTTS() method from onCreate() method;
public void initTTS(){
tts = new TextToSpeech(Translator.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
toast("TTS ready to use");
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
log("Started speaking");
}
#Override
public void onError(String utteranceId) {
log("Error in processing Text to speech");
}
#Override
public void onDone(String utteranceId) {
log("Text to speech finished previewing");
}
});
}
});
}
and there is one more function called
public void speakUpSon(){
HashMap<String, String> params = new HashMap<String, String>();
if(textsToBeSpoken.size() > 0){
for(int i = 0; i < textsToBeSpoken.size(); i++){
if(getCanProceedSpeaking()){
int index = i;
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "finished Speaking of index : " + i);
System.out.println(textsToBeSpoken.get(i));
tts.speak(textsToBeSpoken.get(i)._originalTxt, TextToSpeech.QUEUE_ADD, params);
textsToBeSpoken.remove(index);
}
}
}
}
in other thread somewere in the app i'll be inserting the objects to speak in textsToBeSpoken, and in other thread there'll be loop were it'll check for the size of the textsToBeSpoken if the size > 0, it'll call the speakUpSon() method.
until here everything works fine, but i get the following error messages
08-14 11:42:04.370: E/ActivityThread(4945): Activity com.PI.prototype.translator.Translator has leaked ServiceConnection android.speech.tts.TextToSpeech$Connection#b4669088 that was originally bound here
You have to call tts.shutdown() somewhere in your code, it is best in onStop() and call initTTS(); in onStart()
I am using this kind of text to speech in one of my class in my app(Code edited to show outlook & exact requirement.). I will show some content on my view & if we click the button , I want to play the sound that is by using this texttospeech engine... But for First time it is not playing the sound. From the next click onwards the TEXTTOSPEECH engine is working nicely
Iwant to know how to overcome this issue....
public class LearnActivity extends Activity implements OnClickListener, OnInitListener {
AudioManager audioManager;
float volume;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn);
textToSpeech = new TextToSpeech(this, this);
textToSpeech.setLanguage(Locale.US);
textToSpeech.setSpeechRate(0.95f);
method();
}
public void method(){
bt.setonClickListener(new onClickListener(){
public void onClick(View v){
playSound(datasource.getItemSound);
}
});
}
public void playSound(String sound){
textToSpeech.speak(sound,TextToSpeech.QUEUE_FLUSH,null);
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
NOTE:- This also meet my Requirement, How to play sound from TEXTTOSPEECH engine directly without using any onClicks etc.,... because I also wants to play a startup sound that too with Android's Text-To-Speech engine only...
That's because you are clicking the button before the engine is ready.
You have to check if the TTS engine has successfully initialized on your onInit() method and enable/disable the play button accordingly.
Assuming that bt in your code is some sort of View that has setEnabled(boolean) method:
#Override
public void onInit(int status) {
bt.setEnabled(status == TextToSpeech.SUCCESS);
}
You always have to assume that the engine has not been initialized and hence keep your play button disabled by default.
I used RXJava to make a class that solves this problem. If your TTS engine is not ready when you want to use the speak method it will wait for the engine to get ready and then speaks the given string.
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Pair;
import android.widget.Toast;
import java.util.Locale;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
public class Pronunciation {
private TextToSpeech textToSpeech;
private int languageResult;
private boolean noError;
private final String errorMessage="Something went wrong with your text to speech engine";
private PublishSubject<Boolean> engineIsReady=PublishSubject.create();
private PublishSubject<Pair<String,Integer>> speakObservable=PublishSubject.create();
private CompositeDisposable compositeDisposable=new CompositeDisposable();
public Pronunciation(Context context) {
textToSpeech=new TextToSpeech(context, status -> {
if (status!=TextToSpeech.ERROR){
languageResult= textToSpeech.setLanguage(Locale.ENGLISH);
engineIsReady.onNext(true);
} else {
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}
});
if (languageResult==TextToSpeech.LANG_MISSING_DATA||languageResult== TextToSpeech.LANG_NOT_SUPPORTED){
noError =false;
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}else { noError =true;}
compositeDisposable.add( Observable.combineLatest(speakObservable, engineIsReady,
(stringIntegerPair, aBoolean) -> stringIntegerPair)
.subscribeOn(Schedulers.io())
.subscribe(pair->{
if (noError)
textToSpeech.speak( (pair).first
,(pair).second,null,null);
}));
}
public void speak(String text,int queueMode){
speakObservable.onNext(new Pair<>(text,queueMode));
}
public void stop(){
if (textToSpeech!=null){
textToSpeech.stop();
textToSpeech.shutdown();
}
compositeDisposable.clear();
}
}
first add RxJava dependency in your Gradle file
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Then create an instance of this class in the onCreate method of your activity or fragment.Now you can pass the string and queue mode to the speak method.
pronunciation.speak("Hi", TextToSpeech.QUEUE_FLUSH));
Don't forget to call the stop method in onDestroy or onDetach to avoid memory leak
#Override
public void onDetach() {
super.onDetach();
pronunciation.stop();
}
you should write your program ...
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnUtteranceCompletedListener {
TextToSpeech t1;
protected void onCreate(Bundle savedInstanceState) {
t1=new TextToSpeech(MainActivity.this, MainActivity.this);
}/////on creat
protected void onDestroy() {
if(t1!=null) {
t1.stop();
t1.shutdown();
t1=null;
}
super.onDestroy();
}
public void onInit(int arg0) {
t1.setOnUtteranceCompletedListener(this);
}
}//mainactivity
Add this command when button is clicked or everywhere you want to speak text.
t1.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Just Put Delay For 5 Second And It's Working without any button Click
public class Final_Text_To_Speech_Activity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private TextToSpeech tts; // For Text to Speech
CardView ScanProduct, SearchProduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
init();
// Just Put Delay For 5 Second And It's Working without any button Click
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
SpeakOutOnce("Welcome to Text To Speech Application");
}
}, 5000);
}
#Override
protected void onResume() {
super.onResume();
}
public void init() {
ScanProduct = (CardView) findViewById(R.id.scan_product);
SearchProduct = (CardView) findViewById(R.id.search_product);
// Search On Button Click
ScanProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Scan Option");
}
});
SearchProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Search Option ");
}
});
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
int result = tts.setLanguage(Locale.US);
if (status == TextToSpeech.SUCCESS) {
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
} else {
speakOut("");
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
private void speakOut(String text) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
private void SpeakOutOnce(String text) {
if (tts != null) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}