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 name="voice_url">https://play.google.com/store/apps/details?id=com.google.android.voicesearch.x</string>
<string name="dialog_title">提示</string>
<string name="dialog_content">未找到語音識別設備,是否下載?</string>
<string name="cancel">取消</string>
<string name="download">下載</string>