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.易做图_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.易做图_list_item_1,
matches));
}
在列表中显示由语音识别返回的文字:
作者:mapdigit
补充:移动开发 , Android ,