JamesBrill / react-speech-recognition

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

Fire command on stopListen #73

Closed Nitzahon closed 3 years ago

Nitzahon commented 3 years ago

I know the api lists a way to add an event listener to the onaudioend property of Speech Recognition. I have no luck. basically I'm trying to get a function to fire whenever the speech recognition does it's automatic stopListen (when listening isn't continuous) so that it can update a useState that checks the listening status and shows the right button (on/off).

Do you have an example to show me?

JamesBrill commented 3 years ago

You just need to render different content based on the listening property. Most basic example:

const Dictaphone = () => {
  const { listening } = useSpeechRecognition()
  if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
    return null
  }

  return (
    <div>
      {listening ? 
        <span>Content to show when listening</span> : 
        <span>Content to show when not listening</span>
      }
    </div>
  )
}

If you want to do something when the API stops listening (e.g. updating your state), you can make use of useEffect:

  useEffect(() => {
    if (!listening) {
      // update your state
    }
  }, [listening])
Nitzahon commented 3 years ago

This is perfect. Thank you

eesayas commented 3 years ago

Hi I'm trying this too but my state is not updating back to "when listening". Thanks in advance!

JamesBrill commented 3 years ago

Hi @eesayas Could you elaborate on what you are trying to do and perhaps provide some example code?

I had a look through your code and I'm guessing your issue is here. You just need to add paras and setParas to your list of dependencies in useEffect. Otherwise, your logic inside useEffect will always be referencing the original value of paras (an emptylist). To learn why, read the "Note" under this section in the React docs.