How to check if SpeechRecognizer is currently running?

1.5k views Asked by At

I am trying to track state of SpeechRecognizer, like that:

private SpeechRecognizer mInternalSpeechRecognizer;
private boolean mIsRecording;

public void startRecording(Intent intent) {
 mIsRecording = true;
 // ...
 mInternalSpeechRecognizer.startListening(intent);
}

Problem with that approach is keeping mIsRecording flag up to date is tough, e.g. if there's ERROR_NO_MATCH error should it be set to false or not?
I am under impression some devices stop recording then and others no.

I don't see any method like SpeechRecognizer.isRecording(context), so I am wondering if there's way to query through running services.

1

There are 1 answers

5
N0un On

One solution to handle end or error cases is to set a RecognitionListener to your SpeechRecognizer instance. You must doing it before calling startListening()!

Example:

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 
});

In your case, you can make your class containing the mIsRecording attribute implement RecognitionListener interface. Then, you just have to override these two methods with the following instruction:

mIsRecording = false;

Furthermore, your mIsRecording = true instruction is in the wrong place. you should do it in the onReadyForSpeech(Bundle params) method definition, otherwise, speech recognition may never start while this value is true.

Finally, in the class managing it, juste create methods like:

// 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;
}

Be careful about thread safety for recordingIsRunning calls, and all will be ok :)