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

这个例子需要Android系统中安装了支持RecognizerIntent.ACTION_RECOGNIZE_SPEECH的应用,比如Google的 Voice Search应用。

 

Android ApiDemos示例解析(46):App->Voice Recognition_第1张图片

模拟器上缺省没有安装,可以参见如何在Android emulator上安装 APK 在模拟器上安装一个Voice Search。

本例VoiceRecognition首先通过PackageManager检测本机是否安装了支持RecognizerIntent.ACTION_RECOGNIZE_SPEECH,如果有,则Enable Speak按钮,否则显示“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!”则会启动语音输入对话框:

Android ApiDemos示例解析(46):App->Voice Recognition_第2张图片

Speak按钮对应的代码如下:

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搜索。

下面代码响应从语音输入对话框返回值:

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)); 
}


 

在列表中显示由语音识别返回的文字:

Android ApiDemos示例解析(46):App->Voice Recognition_第3张图片

注:这个例子尽管在模拟器上可以安装Google Voice Search,但似乎Voice Search不能正确运行,本例最好使用手机来测试。

你可能感兴趣的:(android,Web,list,Google,测试,search)