在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來判斷設備是否支持這些功能。