最近项目开发中需求中要采用多种的输入方式,于是乎想起google的语音搜索做了一下尝试,做了一个简单的语音识别的demo,总结起来,大致的过程如下:
一、检查Androird手机上是否装上了google的语音搜索(一般Android的手机都会自带,没有的话需要你自己手动下载)
PackageManager pm = getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities(new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() != 0) {//触发事件 mBtnPlayVoice.setOnClickListener(this);//触发语音识别 mBtnPlayVoice.setOnTouchListener(new BtnRecordVoiceListener()); } else { mBtnPlayVoice.setEnabled(false);二、设置监听,请求google的语音识别
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;加上这一句。具体含义可以参考google语音搜索的api.
private void startVoiceRecognitionActivity() { try { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请对着麦克风说话!"); startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); } catch (Exception e) { e.printStackTrace(); getToast("找不到语音设备"); } } mBtnPlayVoice.setText(“请先装谷歌语音助手”); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) { ArrayList<String> matchResults = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); String voice_str = " "; // for (int i = 0; i < matchresults.size(); i++) { // voice_str += matchresults.get(i).toString(); // }//数组中是匹配到的字符串数组 voice_str = matchResults.get(0).toString();// 只要最相似的就行,去第一个, sendMsg(voice_str);//获得到识别的字符串再进行处理 } super.onActivityResult(requestCode, resultCode, data); }
总的来说,语音识别技术现在都有开放的api可以调用,目前国内还有讯飞语音的api是开放的,整体来说调用第三方的SDK实现起来比较简单,另外,语音识别后面一般还有语音合成(读出来)。是否使用看你的需求了。