I’ve got a problem with TTS in a Service. It acts like it wants to talk but it never does. Watching the LogCat it prints “TTS received: the text it should speak” and I Log when it init’s and that’s showing success. I’ve tried creating a thread for it, that didnt help.
onUtteranceComplete never triggers either. I’ve even done a while loop like this (just for testing):
while(mTTS.isSpeaking()) {
Log.d("", "speaking");
}
…and it’s never speaking
I know TTS is setup correctly because it works in a regular Activity
Here’s my code.
import java.util.HashMap;
import java.util.Locale;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
public class TTSService extends Service implements OnInitListener, OnUtteranceCompletedListener {
TextToSpeech mTTS;
@Override
public void onCreate() {
Log.d("", "TTSService Created!");
mTTS = new TextToSpeech(getApplicationContext(), this);
//I've tried it in a thread....
/*new Thread(new Runnable() {
@Override
public void run() {
HashMap<String, String> myHashStream = new HashMap<String, String>();
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1");
mTTS.setLanguage(Locale.US);
//mTTS.setOnUtteranceCompletedListener(this);
mTTS.speak("I'm saying some stuff to you!", TextToSpeech.QUEUE_FLUSH, myHashStream);
}
}).start();*/
//I've tried it not in a thread...
HashMap<String, String> myHashStream = new HashMap<String, String>();
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashStream.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1");
mTTS.setLanguage(Locale.US);
mTTS.setOnUtteranceCompletedListener(this);
mTTS.speak("I'm saying some stuff to you!", TextToSpeech.QUEUE_FLUSH, myHashStream);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onInit(int status) {
Log.d("", "TTSService onInit: " + String.valueOf(status));
if(status == TextToSpeech.SUCCESS){
Log.d("", "TTS Success");
}
}
public void onUtteranceCompleted(String uttId) {
Log.d("", "done uttering");
if(uttId == "1") {
mTTS.shutdown();
}
}
}
Thanks
Ok, I’ve got it figured out now! What was happening is it was trying to speak before
TTSwas initialized. So in a thread I wait for ready to not == 999. Once its either 1 or anything else we’ll then take care of speaking. This might not be safe putting it in a while loop but… It’s working nonetheless.