I\'m trying to get Android\'s TTS to run inside a service, but I have no idea why it isn\'t working, it compiles, doesn\'t crash, but it just doesn\'t work.
The Toast no
Well, making this question gave me a better answer than I could find with google.
Go to the answer to this question, and change it to fit your application.
TTS doesn't speak from a service whereas it does it from an activity in android
You can do like below: It's working for me. You have to create an activity to start this service, like this: this.startService(intent)
public class TTSService extends Service implements TextToSpeech.OnInitListener{
private String str;
private TextToSpeech mTts;
private static final String TAG="TTSService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
mTts = new TextToSpeech(this,
this // OnInitListener
);
mTts.setSpeechRate(0.5f);
Log.v(TAG, "oncreate_service");
str ="turn left please ";
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
sayHello(str);
Log.v(TAG, "onstart_service");
super.onStart(intent, startId);
}
@Override
public void onInit(int status) {
Log.v(TAG, "oninit");
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.v(TAG, "Language is not available.");
} else {
sayHello(str);
}
} else {
Log.v(TAG, "Could not initialize TextToSpeech.");
}
}
private void sayHello(String str) {
mTts.speak(str,
TextToSpeech.QUEUE_FLUSH,
null);
}
}
https://developer.android.com/reference/android/speech/tts/TextToSpeechService.html
since API Level 14, android has added a default TextToSpeech Service class that does what you want.