1

我在android中使用識別監聽器進行語音識別。我班的基本結構如下:如何在android中等待語音識別的結果?

class SpeechInput implements RecognitionListener { 

    Intent intent; 
    SpeechRecognizer sr; 
    boolean stop; 

    public void init() { 
     sr = SpeechRecognizer.createSpeechRecognizer(context); 
     sr.setRecognitionListener(this); 
     intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
     intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
     intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,context.getPackageName()); 
     intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,3); 
    } 

    ... 

} 

我被困在那裏我想在一個循環中運行Android識別聽衆的情況下,一些過的線路:

for(int i=0; i<N; i++) { 
     // Some processing code 
     sr.startListening(intent); 
} 

現在,我想在輸出開始之前等待輸出。爲了實現這一點,我試圖用鎖定機構如下:

for(int i=0; i<N; i++) { 
     // Some processing code 
     sr.startListening(intent); 
     stop = false; 
     new Task().execute().get(); 
} 

其中任務是定義爲的AsyncTask如下:

private class Task extends AsyncTask<Void,Void,Void> { 

     @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      int counter = 0; 
      while(!stop) { 
       counter++; 
      } 
     } catch(Exception e) { 
     } 
     return null; 
    } 
} 

布爾值「停止」在「onResults被更新'RecognitionListener的方法如下:

public void onResults(Bundle results) { 
    ... 
    stop = true; 
} 

問題是語音識別根本不起作用。什麼都沒有發生,甚至沒有開始。我想這是因爲asyncTask佔用了所有的處理器時間。你能引導我走向一個能夠實現這個目標的建築嗎?謝謝。

回答

3

當您收到結果時重新開始聆聽。無需循環,無需等待。

我不是在Android設備上的語音識別專家,但你可能與呼叫

new Task().execute().get(); 

因此,語音識別可能永遠不會開始封殺主線程。

+0

感謝隊友。解決問題。 – Bhoot 2015-04-06 08:23:23

3

請務必注意,Android 的語音識別API的方法只能從主線程調用,並且所有回調都在應用程序的主線程上執行。

因此,當主線程被阻塞時,識別監聽器也會被阻塞,這就是爲什麼當我嘗試按照問題中所示的方式執行語音識別時沒有任何反應。

以從接受的答案的提示,我用RecognitionListener接口的onResults方法重新啓動偵聽,如下所示:

public void onResults(Bundle results) { 
    ... 
    sr.startListening(intent); 
}