Android调用谷歌语音识别其实很简单,直接利用 intent 跳转到手机里面的谷歌搜索,代码也很简单,直接调用方法 startVoiceRecognitionActivity()
如果大家手机里面没有谷歌搜索,这里会弹出一个下载框给我们选择下载,识别完成后,得到result List数组,里面有很多识别结果,我们获取第一个就可以了。
贴出代码:
/**
* 調用方法
*/
private void startVoiceRecognitionActivity() {
try {
// 通过Intent传递语音识别的模式,开启语音
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// 语言模式和自由模式的语音识别
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// 提示语音开始
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "开始语音");
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "zh-HK");
// 开始语音识别
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
showDialog();
}
}
private void showDialog() {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage(R.string.dialog_content);
builder.setTitle(R.string.dialog_title);
builder.setNegativeButton(R.string.download,
new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Uri uri = Uri.parse(getApplication().getString(R.string.voice_url));
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
}
});
builder.setPositiveButton(R.string.cancel,
new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
&& resultCode == RESULT_OK) {
ArrayList<String> results = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (results.size() > 0) {
voiceView.setText(results.get(0));
} else {
Utils.getInstance().showTextToast("檢測失敗,請重新點擊識別!", context);
}
}
}
<string>https://play.google.com/store/apps/details?id=com.google.android.voicesearch.x</string>
<string>提示</string>
<string>未找到語音識別設備,是否下載?</string>
<string>取消</string>
<string>下載</string>
相关阅读: