我正在开发一个Android应用程序,使用文本转语音功能。当我打开我的应用程序时,我需要运行文本到语音的转换。在完成后,我想做一些事情。我的代码如下:
public class Mainactivity extends Activity implements OnInitListener, OnUtteranceCompletedListener{
private static int REQ_CODE = 1;
private TextToSpeech tts = null;
private boolean ttsIsInit = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startTextToSpeech();
}
private void startTextToSpeech() {
Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, REQ_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_CODE) {
if (resultCode == Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(this, this);
}
else {
Intent installVoice = new Intent(Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installVoice);
}
}
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
ttsIsInit = true;
int result = tts.setOnUtteranceCompletedListener(this);
if (tts.isLanguageAvailable(Locale.ENGLISH) >= 0)
tts.setLanguage(Locale.ENGLISH);
tts.setPitch(5.0f);
tts.setSpeechRate(1.0f);
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE");
tts.speak("hi how are you?", TextToSpeech.QUEUE_FLUSH, myHashAlarm);
}
}
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onUtteranceCompleted(String uttId) {
Toast.makeText(Mainactivity.this,"done", Toast.LENGTH_LONG).show();
if (uttId.equalsIgnoreCase("done")) {
Toast.makeText(Mainactivity.this,"inside done", Toast.LENGTH_LONG).show();
}
}
}
我的应用中,文字转语音功能能够正常工作。但我该如何检测文字转语音是否完成呢?需要帮助......谢谢.....
int result = tts.setOnUtteranceCompletedListener(this);
来设置监听器。检查result
变量的值。应该返回 SUCCESS(0)或 ERROR(-1)。还要在onUtteranceCompleted()
中添加一些日志以查看它是否真的到达了那里。同时检查 logcat 是否有其他奇怪的错误。 - David Wasser