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”

// 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按钮对应的代码如下:

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


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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值