我有一个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方法中使用。
最佳答案
您在onPause中关闭了TextToSpeech,因此mTts不再绑定到文本到语音引擎。如果要做的只是显示识别器对话框,则需要将onPause()中的代码移动到onStop()中。
显示语音识别器对话框时,将调用您的活动onPause(),但不会调用onStop(),除非您的活动不再可见。您还应该在onStart()中再次实例化语音文本。
关于android - Android TextToSpeech.speak在onActivityResult中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22702987/