我有一个speakText()方法如下
public void speakText(){
String toSpeak = "Testing 1 2 3";
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
mTts.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
按下按钮(即从onClick函数调用此方法)可以正常工作。但是当我在onActivityResult()中调用此方法时,如下所示,我听不到任何东西
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_running_ui);
...
speakButton = (Button) findViewById(R.id.speakButton);
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if(activities.size()==0){
speakButton.setEnabled(false);
Toast.makeText(getApplicationContext(), "Speech Recognizer Not Found", 1000).show();
}
speakButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
startVoiceRecognitionActivity();
}
});
commandText = (TextView) findViewById(R.id.command);
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch(requestCode){
case MY_DATA_CHECK_CODE:
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
mTts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
mTts.setLanguage(Locale.UK);
}
});
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
case VOICE_RECOGNITION_REQUEST_CODE:
if (resultCode == RESULT_OK){
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
commandText.setText(matches.get(0)); // get the first matching text
speakText();
}
}
}
@Override
public void onPause(){
if(mTts != null){
mTts.stop();
mTts.shutdown();
}
super.onPause();
}
我要做的是让Android手机在讲话到文本转换后说些什么。我确定该程序进入VOIC_RECOGNITION_REQUEST_CODE分支,因为它使用commandText.setText显示文本(matches.get(0));线。
我不知道为什么textToSpeech使用按钮按下但不在onActivityResult方法内。
答案 0 :(得分:2)
您在onPause中关闭TextToSpeech,因此mTts不再绑定到文本到语音引擎。如果您只是为了显示识别器对话框,则需要将onPause()中的代码移动到onStop()。
当显示语音识别器对话框时,将调用您的活动onPause(),但不会调用onStop(),除非您的活动不再可见。您还应该在onStart()中再次将文本转换为语音。