如何检查SpeechRecognizer当前是否正在运行?
问题描述:
我试图跟踪SpeechRecognizer
状态,这样的:如何检查SpeechRecognizer当前是否正在运行?
private SpeechRecognizer mInternalSpeechRecognizer;
private boolean mIsRecording;
public void startRecording(Intent intent) {
mIsRecording = true;
// ...
mInternalSpeechRecognizer.startListening(intent);
}
问题与方法是保持mIsRecording
标志最新的是艰难的,例如如果有ERROR_NO_MATCH
错误,应该将其设置为false
或者不是?
我在印象之下有些设备停止录音然后和其他人没有。
我没有看到像SpeechRecognizer.isRecording(context)
这样的方法,所以我想知道是否有方法通过运行服务进行查询。
答
处理结束或错误情况的一种解决方案是将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