我有一個speakText()方法如下的Android TextToSpeech.speak不工作onActivityResult
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方法中使用。
發佈您的TextToSpeech代碼onResume和onPause。 –
添加onPause()方法,我沒有明確地獲取onResume()方法。 –