JamesBrill / react-speech-recognition

💬Speech recognition for your React app
https://webspeechrecognition.com/
MIT License
657 stars 119 forks source link

Stop resetTranscript from overriding stopListening #59

Closed JamesBrill closed 3 years ago

JamesBrill commented 3 years ago

There was a bug (https://github.com/JamesBrill/react-speech-recognition/issues/58) in which resetTranscript would turn the microphone on, even when stopListening had just been called.

When any of stopListening, abortListening or resetTranscript are called, the RecognitionManager will first call disconnect, which asks the Web Speech API to stop listening in some way. resetTranscript requests an abort to prevent speech in progress from being picked up immediately after the transcript is reset. It also specifies behaviour to perform when the microphone is actually turned off. Unlike the other two methods, resetTranscript specifies that the microphone be restarted after being aborted.

The callback for this moment is onRecognitionDisconnect. If the microphone was stopped by resetTranscript, it will immediately turn it on again; otherwise, it will remain off. This is where we encounter the issue.

If stopListening is called and then resetTranscript, resetTranscript will be the last method to configure the behaviour on disconnect, which is to restart. When the disconnect finally happens, it will restart the microphone, going against the request of stopListening to keep it turned off.

The solution is to only configure disconnect logic when the microphone is deemed to be turned on. If stopListening gets in first, it sets listening to false. When resetTranscript follows it, it gets blocked by a new condition in disconnect that requires listening to be true, stopping it from overriding the disconnect behaviour.