2014-12-05 130 views
0

我想知道如何讓程序暫停並在開始另一個事件之前等待事件結束,例如我可以有一段文字到語音,說什麼,然後谷歌語音識別器應該觸發,但是它們同時發射並且使得語音識別器傾聽文本到語音。我試着在這裏搜索一下,發現了一些答案,但他們不是很清楚,任何人都可以幫我解決這個問題嗎?android在等什麼東西

這裏有一個例子代碼,我測試了:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_menu); 

    tts=new TextToSpeech(getApplicationContext(), 
      new TextToSpeech.OnInitListener() { 
      @SuppressWarnings("deprecation") 
      @Override 
      public void onInit(int status) { 
      if(status != TextToSpeech.ERROR){ 
       tts.setLanguage(Locale.UK); 
       tts.speak("Welcome", TextToSpeech.QUEUE_FLUSH, null); 
       }    
      } 
      }); 

    if(!(tts.isSpeaking())){ 
     startVoiceRecognitionActivity(); 
    } 
} 

private void startVoiceRecognitionActivity() 
{ 
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
      RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Up"); 
    startActivityForResult(intent, REQUEST_CODE); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) 
    { 
     matches = data.getStringArrayListExtra(
       RecognizerIntent.EXTRA_RESULTS); 
     if (matches.contains("list")){ 
       Intent gotoList = new Intent(MenuActivity.this, ListActivity.class); 
       startActivity(gotoList); 
     } 
    } 
    super.onActivityResult(requestCode, resultCode, data); 
} 

回答

2

歡迎的異步事件的精彩世界。

爲了做你想做的事,這個方法不是「等待」(因爲一切都會凍結),而是「聽」。

當Android需要很長的時間,比如文本到語音,您必須要監聽一個事件。

如果你看一下文檔的文本到語音的對象,你會發現它接受不同事物的聽衆:http://developer.android.com/reference/android/speech/tts/TextToSpeech.html#setOnUtteranceProgressListener(android.speech.tts.UtteranceProgressListener)http://developer.android.com/reference/android/speech/tts/UtteranceProgressListener.html

所以,你會怎麼做(假設你的文本到語音對象tts):

tts.setOnUtteranceProgressListener(new UtteranceProgressListener() { 

    public void onDone(String utteranceId) { 
     // The text has been read, do your next action 

    } 

    public void onError(String utteranceId, int errorCode) { 
     // Error reading the text with code errorCode, can mean a lot of things 

    } 

    public void onStart(String utteranceId) { 
     // Reading of a sentence has just started. You could for example print it on the screen 

    } 
}); 

這就是所謂的「訂閱事件」,並且是異步的,因爲你的程序可以做其他事情,當「東西」(你已經訂閱),您也會收到通知。

再比如說,當你做

tts.speak ("welcome", ....) 

而且它完成,在監聽的方法onDone將被調用。你可以在那裏啓動語音識別器。

+0

非常有用,它沒有解決我的問題,但與您的鏈接和一些搜索,我發現如何做到這一點,非常感謝你這個有用的信息+1 – mrahmat 2014-12-06 10:00:14