Android ApiDemos示例解析(46):App->Voice Recognition

這個例子需要Android系統中安裝瞭支持RecognizerIntent.ACTION_RECOGNIZE_SPEECH的應用,比如Google的 Voice Search應用。

 

 

模擬器上缺省沒有安裝,可以參見如何在Android emulator上安裝 APK 在模擬器上安裝一個Voice Search。

本例VoiceRecognition首先通過PackageManager檢測本機是否安裝瞭支持RecognizerIntent.ACTION_RECOGNIZE_SPEECH,如果有,則Enable Speak按鈕,否則顯示“Recognizer not present”

[java] 
// Check to see if a recognition activity is present   
PackageManager pm = getPackageManager();  
List<ResolveInfo> activities = pm.queryIntentActivities(  
 new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);  
if (activities.size() != 0) {  
 speakButton.setOnClickListener(this);  
} else {  
 speakButton.setEnabled(false);  
 speakButton.setText("Recognizer not present");  

// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
 new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
 speakButton.setOnClickListener(this);
} else {
 speakButton.setEnabled(false);
 speakButton.setText("Recognizer not present");
}

 

如果本機上安裝瞭Google的Voice Search,點擊“Speak!”則會啟動語音輸入對話框:

 

Speak按鈕對應的代碼如下:

[java] 
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,  
 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);  
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");  
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); 
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

 

采用的是startActivityForResult這是因為我們需要從語音輸入對話框獲取用戶輸入。RecognizerIntent.EXTRA_PROMPT定義對應框提示。 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM 為語音輸入類型,這裡使用自由格式,另外一種為WEB_SEARCH主要用於Web搜索。

下面代碼響應從語音輸入對話框返回值:

[java] 
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE  
    && resultCode == RESULT_OK) {  
 // Fill the list view with the strings the recognizer   
// thought it could have heard   
 ArrayList<String> matches = data.getStringArrayListExtra(  
 RecognizerIntent.EXTRA_RESULTS);  
 mList.setAdapter(new ArrayAdapter<String>(this,  
  android.R.layout.simple_list_item_1,  
 matches));  

if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
    && resultCode == RESULT_OK) {
 // Fill the list view with the strings the recognizer
// thought it could have heard
 ArrayList<String> matches = data.getStringArrayListExtra(
 RecognizerIntent.EXTRA_RESULTS);
 mList.setAdapter(new ArrayAdapter<String>(this,
  android.R.layout.simple_list_item_1,
 matches));
}

 

在列表中顯示由語音識別返回的文字:

 

作者:mapdigit

 

發佈留言