I am developing android application in which I am using text to speech conversion.What I need when I open my application run text to speech conversion. After completion of t
Call the setOnUtteranceCompletedListener inside the onInit function of the tts object.
If you want to make any changes to the UI on the call of the onUtteranceCompleted function, add the code inside a runOnUIThread method.
And do remember to add the Hashmap param value while calling the speak() function
Example :
TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {
@Override
public void onInit(int status) {
mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//UI changes
}
});
}
});
}
});
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");
tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params);
Here is some code from here that helps you be backward compatible so you don't have to target 15.
private void setTtsListener()
{
final SpeechRecognizingAndSpeakingActivity callWithResult = this;
if (Build.VERSION.SDK_INT >= 15)
{
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");
}
}
else
{
int listenerResult = tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener()
{
@Override
public void onUtteranceCompleted(String utteranceId)
{
callWithResult.onDone(utteranceId);
}
});
if (listenerResult != TextToSpeech.SUCCESS)
{
Log.e(TAG, "failed to add utterance completed listener");
}
}
}
If you are using API level 15 or later you can set a progress listener on your TextToSpeech
reference using
setOnUtteranceProgressListener(UtteranceProgressListener listener)
You will get callbacks reporting the progress of the TTS, including a callback when it is finished. See http://developer.android.com/reference/android/speech/tts/TextToSpeech.html and http://developer.android.com/reference/android/speech/tts/UtteranceProgressListener.html
However, I notice that you're already using the deprecated OnUtteranceCompletedListener
. Are you getting the callbacks on onUtteranceCompleted()
? That should also work.