4

我正在尝试跟踪 的状态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),所以我想知道是否有办法通过正在运行的服务进行查询。

4

1 回答 1

-2

处理结束或错误情况的一种解决方案是将 a 设置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;
}

注意记录IsRunning调用的线程安全,一切都会好的:)

于 2017-08-17T16:35:55.937 回答