小迈 2012-03-20
首先,你的设备要支持语音识别,这属于android的一个框架,如果是手机的话,安装google的语音识别包就可以了.模拟器还没有试过能否通过安装来支持语音识别.
private void startVoiceRecognitionActivity() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); // 设置语言格式,使用免费的语音识别支持的语言. intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); // 设置提示文字,设备进行语音采集时,屏幕上的提示语 intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请对准话筒说话"); mActivity .startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); }
可以看到语音设别是通过intent启动的,识别结束之后,会将数据返回原来的activity.
所以需要重写onActivityResult方法.
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) { final ArrayList<String> matches = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); Builder builder = new AlertDialog.Builder(this); mList = new ListView(this); mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches)); builder.setView(mList); final AlertDialog dialog = builder.create(); dialog.show(); } super.onActivityResult(requestCode, resultCode, data); }