I wrote the following code:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private TextToSpeech mTTS;
@Override
protected void onPause() {
super.onPause();
if (mTTS != null) {
mTTS.stop();
mTTS.shutdown();
}
}
@Override
protected void onResume() {
super.onResume();
mTTS = new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
mTTS.setLanguage(Locale.ENGLISH);
mTTS.speak("Hello!", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
}
public void onButtonClick(View view) {
mTTS.speak("Hello!", TextToSpeech.QUEUE_FLUSH, null);
}
}
But this code: mTTS = new TextToSpeech(... freezes the UI thread for 5–8 seconds.
I noticed that the delay happens on this line in logcat (first line):
07-13 11:51:11.304 5296-5296/com.example.TextToSpeachTest I/TextToSpeech﹕ Connected to ComponentInfo{com.google.android.tts/com.google.android.tts.service.GoogleTTSService}
07-13 11:51:17.317 5296-5296/com.example.TextToSpeachTest I/Choreographer﹕ Skipped 391 frames! The application may be doing too much work on its main thread.
I tried to put it inside AsyncTask:
@Override
protected void onResume() {
super.onResume();
MyAsyncTask newTask = new MyAsyncTask() {
protected void onPostExecute(Boolean result) {
}
};
newTask.context = getApplicationContext();
newTask.execute();
}
...
class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private TextToSpeech mTTS;
public Context context;
@Override
protected Boolean doInBackground(Void... arg0) {
mTTS = new TextToSpeech(context,
new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
mTTS.setLanguage(Locale.ENGLISH);
mTTS.speak("Hello!", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
return true;
}
}
But nothing changed. Could you please advise a proper solution/idea?
This delay manifests on my Phone LG L4 II (E440). On Nexus 10 – no delays. I tried different talking apps from Play Store on my LG L4. On some apps there is also UI blocking, but some work without the blocking. This means – it is possible to implement. But how?