我正在将TextToSpeech合并到GCM gcmquickstart示例中。 收到来自谷歌服务器的消息后,我尝试使用tts说出来。 在说话之前,总是会去发动。 但如果使用调试模式,tts可以正常工作。 代码如下:
public class MyGcmListenerService extends GcmListenerService implements TextToSpeech.OnInitListener {
private static final String TAG = "MyGcmListenerService";
private TextToSpeech tts;
private String ttsMessage;
public void onInit(int code) {
if (code == TextToSpeech.SUCCESS) {
if (tts != null) {
if (Charset.forName("US-ASCII").newEncoder().canEncode(ttsMessage)) {
tts.setLanguage(Locale.ENGLISH);
} else {
tts.setLanguage(Locale.CHINESE);
}
tts.speak(ttsMessage, TextToSpeech.QUEUE_FLUSH, null);
Log.d(TAG, "tts speak!!!");
}
Log.d(TAG, "tts initialized!!!");
} else {
tts = null;
}
}
public void onDestroy() {
//Close the Text to Speech Library
if(tts != null) {
tts.stop();
tts.shutdown();
Log.d(TAG, "TTS Destroyed");
}
super.onDestroy();
}
public void onMessageReceived(String from, Bundle data) {
ttsMessage = message;
if (tts == null) {
tts = new TextToSpeech(this, this);
}
}
// [END receive_message]
}
答案 0 :(得分:0)
我找到了解决方案,而不是最好的解决方案,但它确实有效。
在onMessageReceived中运行一个无限循环,这使得tts不被破坏。 当tts完成它的工作时,跳出循环。
public class MyGcmListenerService extends GcmListenerService implements TextToSpeech.OnInitListener {
private static final String TAG = "MyGcmListenerService";
private TextToSpeech tts;
private String ttsMessage;
private boolean keepAlive = true;
@Override
public void onInit(int code) {
if (code == TextToSpeech.SUCCESS) {
if (tts != null) {
if (Charset.forName("US-ASCII").newEncoder().canEncode(ttsMessage)) {
tts.setLanguage(Locale.ENGLISH);
} else {
tts.setLanguage(Locale.CHINESE);
}
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
keepAlive = false;
}
@Override
public void onError(String utteranceId) {
}
});
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"messageID");
tts.speak(ttsMessage, TextToSpeech.QUEUE_FLUSH, map);
}
Log.d(TAG, "tts speak!!!");
} else {
tts = null;
keepAlive = false;
}
}
public void onDestroy() {
//Close the Text to Speech Library
if(tts != null) {
tts.stop();
tts.shutdown();
Log.d(TAG, "TTS Destroyed");
}
super.onDestroy();
}
public void onMessageReceived(String from, Bundle data) {
ttsMessage = message;
if (tts == null) {
tts = new TextToSpeech(this, this);
}
keepAlive = true;
while (keepAlive) {
Log.d(TAG, "looping");
;
}
}
}