2014-03-28 79 views
1

我有一個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方法中使用。

+0

發佈您的TextToSpeech代碼onResume和onPause。 –

+0

添加onPause()方法,我沒有明確地獲取onResume()方法。 –

回答

2

您關閉了onPause中的TextToSpeech,因此mTts不再綁定到文本到語音引擎。如果您只是爲了顯示識別器對話框,則需要將onPause()中的代碼移動到onStop()。

當語音識別器對話框顯示時,您的活動onPause()被調用,但不是onStop(),除非您的活動不再可見。您還應該在onStart()中再次將文本固定爲語音。

+0

它的工作!謝謝。這正是問題所在 - 語音識別讓應用程序進入暫停狀態。 –