在Android中使用SpeechRecognizer,您需要遵循以下步骤:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
SpeechRecognizer speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
public class MyRecognitionListener implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle params) {
// 当语音识别准备好时调用
}
@Override
public void onBeginningOfSpeech() {
// 当开始说话时调用
}
@Override
public void onRmsChanged(float rmsdB) {
// 当音量变化时调用
}
@Override
public void onBufferReceived(byte[] buffer) {
// 当接收到音频数据时调用
}
@Override
public void onEndOfSpeech() {
// 当说话结束时调用
}
@Override
public void onError(int error) {
// 当发生错误时调用
}
@Override
public void onResults(Bundle results) {
// 当获得语音识别结果时调用
}
@Override
public void onPartialResults(Bundle partialResults) {
// 当获得部分语音识别结果时调用
}
@Override
public void onEvent(int eventType, Bundle params) {
// 当发生其他事件时调用
}
}
MyRecognitionListener listener = new MyRecognitionListener();
speechRecognizer.setRecognitionListener(listener);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
speechRecognizer.startListening(intent);
speechRecognizer.stopListening();
@Override
protected void onDestroy() {
super.onDestroy();
if (speechRecognizer != null) {
speechRecognizer.destroy();
}
}
注意:在使用SpeechRecognizer之前,请确保您的设备支持语音识别功能。可以通过检查PackageManager的FEATURE_MICROPHONE和FEATURE_VOICE_RECOGNITION来判断设备是否支持这些功能。