Text to Speech from String array in Android? - android

I have created a slideshow app in Android Studio and I want the string to be converted to speech.
How do I do that? Please look at the speak() after QUEUE_FLUSH.
Thank you in advance.
public class Level1 extends Activity {
int i= 0;
static final String[] texts ={"hi", "bear", "hat"};
TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
tts = new TextToSpeech(Level1.this, new TextToSpeech.OnInitListener() {
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.US);
tts.speak(texts,TextToSpeech.QUEUE_FLUSH,????? ); //What do I put here?
} else {
Toast.makeText(getApplicationContext(),
"Feature not Supported in Your Device",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onPause() {
if (tts!= null) {
tts.stop();
tts.shutdown();
}
super.onPause();
}

simple put null there
tts.speak(texts,TextToSpeech.QUEUE_FLUSH,null);
try this
Edit 1:
use utterancecompletelistener...it will be called once it finishes calling hi...then you can again call speak from there...and this time change the method
tts.speak(texts[1],TextToSpeech.QUEUE_ADD,null);
or you can simply concate the string array
tts.speak(texts[0]+" "+texts[1]+" "+texts[2],TextToSpeech.QUEUE_FLUSH,null);

It should be null
public class Level1 extends Activity {
int i= 0;
static final String[] texts ={"hi", "bear", "hat"};
TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
tts = new TextToSpeech(Level1.this, new TextToSpeech.OnInitListener() {
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.US);
tts.speak(texts,TextToSpeech.QUEUE_FLUSH,null); // ????--> null
} else {
Toast.makeText(getApplicationContext(),
"Feature not Supported in Your Device",
Toast.LENGTH_SHORT).show();
}
}
});
}
tts.speak(texts,TextToSpeech.QUEUE_FLUSH,null);
and if you want more reference you can find it here
public int speak (String text, int queueMode, HashMap<String, String> params)
Here
params -->
Parameters for the request. Can be null. Supported parameter names: KEY_PARAM_STREAM, KEY_PARAM_UTTERANCE_ID, KEY_PARAM_VOLUME, KEY_PARAM_PAN. Engine specific parameters may be passed in but the parameter keys must be prefixed by the name of the engine they are intended for. For example the keys "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the engine named "com.svox.pico" if it is being used.

Related

Utterance progress listener doesnot get called even after passing a hash map parameter

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.

Text to Speech is not working during an incoming call in android

I want to play a text sequence as speech during an incoming call , lowering the ringtone for few seconds. I've sent the string via intent from a broadcast receiver to another class file.
The text is displayed if I use it in toast during call but the speech doesn't play.
the code for text to speech in my class file is :-
public class callName extends Activity {
String call;
TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
call = extras.getString("sms");
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.US);
}
}
});
Toast.makeText(getBaseContext(), call, Toast.LENGTH_LONG).show();
tts.speak(call, TextToSpeech.QUEUE_FLUSH, null);
}
}
tts has not been initialize when you call speak, you have to move your speak code inside onInit()
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR) {
tts.setLanguage(Locale.US);
tts.speak(call, TextToSpeech.QUEUE_FLUSH, null);
}
}
});

Android text to speech setOnUtteranceCompleted not applicable

I'm trying to get the activity to finish after it's finished speaking but for some reason I cannot fathom it tells me that the setOnUtteranceCompleted not applicable for text to speech. I'm new to android programming so please be gentle :-)
Here's the code...
public class SpeakActivity extends Activity implements OnUtteranceCompletedListener{
Random randnum = new Random();
TextToSpeech tts = null;
private boolean ttsIsInit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speak);
// Show the Up button in the action bar.
setupActionBar();
startTextToSpeech();
}
void startTextToSpeech(){
final int randint = randnum.nextInt(4);
final String text = ((GlobVars) this.getApplication()).getResponse(randint);
tts = new TextToSpeech(this, new OnInitListener() {
public void onInit(int status) {
tts.setOnUtteranceCompletedListener(this);
if (status == TextToSpeech.SUCCESS) {
ttsIsInit = true;
if (tts.isLanguageAvailable(Locale.ENGLISH) >= 0){
tts.setLanguage(Locale.ENGLISH);
}
tts.setPitch(0.5f);
tts.setSpeechRate(0.5f);
if (tts != null && ttsIsInit) {
Log.d("got ere", "spoken");
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
}
});
}
// shut down tts to free the TTS resources
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onUtteranceCompleted(String arg0) {
((GlobVars) this.getApplication()).setListen(true);
this.finish();
}
}
I am ot sure but as per the docs of setOnUtteranceCompletedListener(), you might need to use TextToSpeech.OnUtteranceCompletedListener listener as an argument. I think the way to use the function is as below. Note that use runOnUIThread method in case you want to make any changes to the UI on the call of the onUtteranceCompleted function.
TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {
#Override
public void onInit(int status) {
tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String utteranceId) {
//Do things here
}
});
}
});
Source of above : Check onUtteranceCompleted does not get called? question.
Hope this helps.

Text to speech Manager doesn't work

I created some TTS Manager, because I want use someTTsObject.speak("some string") in other classes.
This is my Manager class:
public class TtsManager
{
private TextToSpeech myTTS;
private Context context;
public TtsManager(Context baseContext)
{
this.context = baseContext;
initOrInstallTts();
}
public void initOrInstallTts()
{
myTTS = new TextToSpeech(context, new OnInitListener()
{
public void onInit(int status)
{
if (status == TextToSpeech.SUCCESS)
{
myTTS.setLanguage(Locale.US);
}
else
installTts();
}
});
}
private void installTts()
{
Intent installIntent = new Intent();
installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
context.startActivity(installIntent);
}
public void speak(String text)
{
myTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
and this is my main class, where I want to use that:
public class main extends Activity {
TtsManager tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TtsManager(this);
tts.speak("Welcome in my app");
}
}
When I run compilation I see on the LogCat:
08-30 17:25:52.531: I/TTS received:(2782): Welcome in my app
but i don't hear any text. I tested it on the virtual machine and phone.
Why that doesn't work?
Cheers!
Ok, the problem is that you are not waiting until the callback comes from the system telling you the TTS is initialized. You can't call speak until onInit is called with a SUCCESS value.
problem is that you are calling speak function without initializing tts engine....
add
tts.initOrInstallTts();
after
tts = new TtsManager(this);
Like:
public class main extends Activity {
TtsManager tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TtsManager(this);
tts.initOrInstallTts();
tts.speak("Welcome in my app");
}
}

TextToSpeech.OnInitListener.onInit(int) being called continuously

I'm getting reports that, on some (not all) HTC Desire HD (FRF91, 2.2) and HTC EVO 4G ( PC36100|3.29.651.5, 2.2), the TextToSpeech.OnInitListener.onInit(int) is being called repeatedly (over 1500 times in the space of a few seconds) on the same object. This behaviour does not occur for any of my other users (or with other Desire HD users) AFAICT.
The code is:
TextToSpeech tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
private int mCallCount = 0; // trying to investigate potential infinite loops
#Override
public void onInit(int status) {
if ((mCallCount % 100) == 1) {
// report this
}
mCallCount++;
}
});
Anyone any ideas?
EDIT: I have also tried calling the shutdown() method (the first time multiple listener calls are detected) but this doesn't seem to help.
Maybe you should get around it with your own intermediary method, for example:
private long lastCall = 0;
private long deepBreath = 5*1000; //5 seconds
private boolean hasRested;
TextToSpeech tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
long thisCall = Calendar.getInstance().getTimeInMillis();
intermediaryMethod(status, thisCall);
}
});
//new method
public void intermediaryMethod(int status, long thisCall) {
hasRested = (thisCall-lastCall)>=deepBreath;
if (hasRested) {
lastCall = thisCall;
//do something about 'status'
}
}
This may or may not help, but I had a similar problem when call tts from a service, luckily for me I was better off doing my tts from an activity which solved the problem.
If you do this, and it is appropriate, make sure your manifest for the activity has:
android:finishOnTaskLaunch="true"
Try to create object of the Textospeech before on create ie. globally .try this code and check is it still calling many times????
public class TtsActivity extends Activity implements OnInitListener {
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private EditText inputText;
private Button speakButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputText = (EditText) findViewById(R.id.input_text);
speakButton = (Button) findViewById(R.id.speak_button);
speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = inputText.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(TtsActivity.this, "Saying: " + text, Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(TtsActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(TtsActivity.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
}

Categories

Resources