2016-04-07 11 views
13

我正在構建一個使用語音命令來執行某些功能的應用程序。我從here用「Ok Google」這樣的詞組開始語音識別?

private static final int SPEECH_REQUEST_CODE = 0; 

// Create an intent that can start the Speech Recognizer activity 
private void displaySpeechRecognizer() { 
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
      RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
// Start the activity, the intent will be populated with the speech text 
    startActivityForResult(intent, SPEECH_REQUEST_CODE); 
} 

// This callback is invoked when the Speech Recognizer returns. 
// This is where you process the intent and extract the speech text from the intent. 
@Override 
protected void onActivityResult(int requestCode, int resultCode, 
     Intent data) { 
    if (requestCode == SPEECH_REQUEST_CODE && resultCode == RESULT_OK) { 
     List<String> results = data.getStringArrayListExtra(
       RecognizerIntent.EXTRA_RESULTS); 
     String spokenText = results.get(0); 
     // Do something with spokenText 
    } 
    super.onActivityResult(requestCode, resultCode, data); 
} 

一些代碼工作。然而,這種方法需要通過點擊一個按鈕來激活。有沒有辦法通過語音命令啓動語音識別器?像Google Now一樣,您可以只說「Ok Google」,那麼它將打開語音識別器活動並偵聽命令?

謝謝。

回答

2

您需要編寫一個連續語音識別服務。並根據您的語音檢測您的觸發短語並採取行動得到的輸入。

這可能是內存密集型的,您需要通過在適當的時間和屏幕上啓動和停止服務來進行優化。

this question的接受答案提供了實現類似事物的方法。