處理結束或錯誤情況的一種解決方案是將RecognitionListener
設置爲SpeechRecognizer
實例。你必須這樣做之前致電startListening()
!
例子:
mInternalSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
// Other methods implementation
@Override
public void onEndOfSpeech() {
// Handle end of speech recognition
}
@Override
public void onError(int error) {
// Handle end of speech recognition and error
}
// Other methods implementation
});
在你的情況,你可以讓你的類包含mIsRecording
屬性實現RecognitionListener
接口。然後,你就必須重寫這兩種方法有以下指令:
mIsRecording = false;
此外,你mIsRecording = true
指令是在錯誤的地方。您應該在onReadyForSpeech(Bundle params)
方法定義中執行此操作,否則,在此值爲true時語音識別可能永遠不會啓動。
最後,在類管理它,中庸之道創建如下方法:
// Other RecognitionListener's methods implementation
@Override
public void onEndOfSpeech() {
mIsRecording = false;
}
@Override
public void onError(int error) {
mIsRecording = false;
// Print error
}
@Override
void onReadyForSpeech (Bundle params) {
mIsRecording = true;
}
public void startRecording(Intent intent) {
// ...
mInternalSpeechRecognizer.setRecognitionListener(this);
mInternalSpeechRecognizer.startListening(intent);
}
public boolean recordingIsRunning() {
return mIsRecording;
}
注意有關recordingIsRunning調用線程安全的,一切都會好起來:)
正如我在一個問題中提到,如果'onError'正在執行,那麼* not *表示設備停止錄製音頻。如果是ERROR_NO_MATCH,有時會停止錄製,有時不會。 – Piotr
如果你在'ERROR_NO_MATCH'的情況下調用'stopListening()'會怎麼樣? – N0un
但是如果設備想繼續播放,我不想停止錄製。 – Piotr