在评估了几种第三方语音识别选项之后,谷歌语音识别是最准确的。使用谷歌语音识别有两种基本方法。最简单的方法是启动一个意图并相应地处理结果:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE );
在你的onActivityResults()方法中,你需要处理服务返回的匹配结果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
if (matches != null) {
handleResults(matches);
}
}
}
第二种方法更复杂,但允许更好地处理在识别服务运行时可能发生的错误条件。使用此方法,您将创建自己的识别监听器和回调方法。例如:
开始侦听:
mSpeechRecognizer.startListening(mRecognizerIntent)
mRecognizerIntent是什么:
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(getBaseContext());
mSpeechRecognizer.setRecognitionListener(mRecognitionListener);
mRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mRecognizerIntent.putExtra("calling_package", "com.you.package");
然后,创建您的监听器:
private RecognitionListener mRecognitionListener = new RecognitionListener() {
public void onBufferReceived(byte[] buffer) {
}
public void onError(int error) {
public void onEvent(int eventType, Bundle params) {
Log.d(TAG, "onEvent");
}
public void onPartialResults(Bundle partialResults) {
Log.d(TAG, "onPartialResults");
}
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "onReadyForSpeech");
}
public void onResults(Bundle results) {
Log.d(TAG, ">>> onResults");
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
handleResults(matches);
}
public void onRmsChanged(float rmsdB) {
}
public void onBeginningOfSpeech() {
Log.d(TAG, "onBeginningOfSpeech");
}
public void onEndOfSpeech() {
Log.d(TAG, "onEndOfSpeech");
}
};
你可以将你的handleResults()添加进去,以实现你想要的任何操作。