2010-06-15 200 views

回答

10

讓我剪切並粘貼一下,告訴你你需要什麼代碼。

編輯:你也可以從this project下載一個方便的抽象類。

您將需要此意圖(參數,你認爲合適):

public Intent getRecognizeIntent(String promptToUse, int maxResultsToReturn) 
{ 
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
      RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResultsToReturn); 
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, promptToUse); 
    return intent; 
} 

然後,你需要你的意圖發送到像這樣的語音識別活動,

public void gatherSpeech(String prompt) 
{ 
    Intent recognizeIntent = getRecognizeIntent(prompt); 
    try 
    { 
     startActivityForResult(recognizeIntent, SpeechGatherer.VOICE_RECOGNITION_REQUEST_CODE); 
    } 
    catch (ActivityNotFoundException actNotFound) 
    { 
     Log.w(D_LOG, "did not find the speech activity, not doing it"); 
    } 
} 

然後你需要讓你的活動處理語音結果:

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{ 
    Log.d("Speech", "GOT SPEECH RESULT " + resultCode + " req: " 
     + requestCode); 
    if (requestCode == SpeechGatherer.VOICE_RECOGNITION_REQUEST_CODE) 
    { 
     if (resultCode == RESULT_OK) 
     { 
      ArrayList<String> matches = data 
          .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); 
      Log.d(D_LOG, "matches: "); 
      for (String match : matches) 
      { 
       Log.d(D_LOG, match); 
      } 
     } 
    } 
} 
+1

如何檢測標點符號?我嘗試了上面的代碼,試着用「?」來表示問號,逗號用於「,」,指向「。」。 ,沒有任何工作。 – 2011-09-08 10:55:04

+0

不幸的是,沒有辦法識別標點符號。 – gregm 2012-01-26 10:33:03

+0

谷歌不會返回標點符號。例如,如果我說「嘿,你在做什麼?」,谷歌的一個解釋很可能就是「嘿,你在做什麼」。沒有逗號,沒有問號。 – Joey 2012-03-27 04:47:06

0

首先需要顯示谷歌語音輸入對話框,像這樣

/** 
* Showing google speech input dialog 
* */ 
private void promptSpeechInput() { 
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); 
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
      RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); 
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); 
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, 
      getString(R.string.speech_prompt)); 
    try { 
     startActivityForResult(intent, REQ_CODE_SPEECH_INPUT); 
    } catch (ActivityNotFoundException a) { 
     Toast.makeText(getApplicationContext(), 
       getString(R.string.speech_not_supported), 
       Toast.LENGTH_SHORT).show(); 
    } 
} 

則需要接受像這樣的語音輸入。

/** 
* Receiving speech input 
* */ 
@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    switch (requestCode) { 
     case REQ_CODE_SPEECH_INPUT: { 
      if (resultCode == RESULT_OK && null != data) { 

       ArrayList<String> result = data 
         .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); 
       txtSpeechInput.setText(result.get(0)); 
      } 
      break; 
     } 

    } 
} 

和需要設置REQ_CODE_SPEECH_INPUT

​​