6 package com.google.appinventor.components.runtime.util;
8 import android.app.Activity;
9 import android.content.Intent;
10 import android.speech.tts.TextToSpeech;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.Locale;
16 import android.util.Log;
18 import android.os.Handler;
36 private static final String LOG_TAG =
"InternalTTS";
38 private final Activity activity;
40 private TextToSpeech tts;
41 private volatile boolean isTtsInitialized;
43 private Handler mHandler =
new Handler();
45 private int nextUtteranceId = 1;
48 private int ttsRetryDelay = 500;
53 private int ttsMaxRetries = 20;
56 this.activity = activity;
57 this.callback = callback;
61 private void initializeTts() {
63 Log.d(LOG_TAG,
"INTERNAL TTS is reinitializing");
64 tts =
new TextToSpeech(activity,
new TextToSpeech.OnInitListener() {
66 public void onInit(
int status) {
67 if (status == TextToSpeech.SUCCESS) {
68 isTtsInitialized =
true;
76 public void speak(
final String message,
final Locale loc) {
77 Log.d(LOG_TAG,
"Internal TTS got speak");
78 speak(message, loc, 0);
82 return isTtsInitialized;
86 private void speak(
final String message,
final Locale loc,
final int retries) {
87 Log.d(LOG_TAG,
"InternalTTS speak called, message = " + message);
88 if (retries > ttsMaxRetries) {
89 Log.d(LOG_TAG,
"max number of speak retries exceeded: speak will fail");
94 if (isTtsInitialized) {
95 Log.d(LOG_TAG,
"TTS initialized after " + retries +
" retries.");
97 tts.setOnUtteranceCompletedListener(
100 public void onUtteranceCompleted(String utteranceId) {
103 activity.runOnUiThread(
new Runnable() {
111 HashMap<String, String> params =
new HashMap<String, String>();
112 params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, Integer.toString(nextUtteranceId++));
113 int result = tts.speak(message, tts.QUEUE_FLUSH, params);
114 if (result == TextToSpeech.ERROR) {
115 Log.d(LOG_TAG,
"speak called and tts.speak result was an error");
119 Log.d(LOG_TAG,
"speak called when TTS not initialized");
120 mHandler.postDelayed(
new Runnable() {
123 "delaying call to speak. Retries is: " + retries +
" Message is: " + message);
124 speak(message, loc, retries + 1);
132 Log.d(LOG_TAG,
"Internal TTS got onStop");
138 Log.d(LOG_TAG,
"Internal TTS got onDestroy");
141 isTtsInitialized =
false;
148 Log.d(LOG_TAG,
"Internal TTS got onResume");
159 tts.setSpeechRate(speechRate);
164 return tts.isLanguageAvailable(loc);