JamesBrill / react-speech-recognition

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

Unable to stop re rendering on hotword/wake word found in transcript #24

Closed hvardhan617 closed 4 years ago

hvardhan617 commented 4 years ago

How do i stop re render or processing the transcript once the configured wakeword is found. Here is the code snippet i am using.

class Dictaphone extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isWakeWordFound: false
        };
    }
    componentWillMount() {
        const { recognition } = this.props;
        recognition.lang = 'en-US';
        recognition.interimResults = true;
        recognition.maxAlternatives = 3;
    }

    componentDidMount() {
        // this.props.startListening();
    }

    checkForWakeword = (transcript) => {
        if (!this.state.isWakeWordFound) {
            for (const ww in wakeWords) {
                if (transcript.trim().toLowerCase().includes(wakeWords[ww])) {
                    console.log('Wake word found');
                    this.setState({
                        isWakeWordFound: true
                    });
                    // return true;
                }
            }
        }
        // return false;
    };
    render() {
        const {
            transcript,
            finalTranscript,
            startListening,
            abortListening,
            resetTranscript,
            browserSupportsSpeechRecognition
        } = this.props;
        if (!browserSupportsSpeechRecognition) {
            return null;
        }
        console.log('Transcript::::' + transcript);

        return (
            <div>
                {!this.state.isWakeWordFound ? this.checkForWakeword(transcript) : null}
                {this.state.isWakeWordFound ? abortListening() : null}
                <Button onClick={resetTranscript}>Reset</Button>
                <span>{transcript}</span>
            </div>
        );
    }
}

The end goal is to abort Listening whenever a hotword is found.How do i achieve this?

Right now even though, abort Listning is being called once, due to transcript in render props, it is constantly unable to update the state, hence throwing the below error in console.

image

JamesBrill commented 4 years ago

Hi @hvardhan617

A few pointers:


      componentWillReceiveProps(nextProps) {
        const { transcript, abortListening } = this.props;
        // If transcript has changed and it contains a wake word, stop listening
        if (transcript !== nextProps.transcript &&
            containsWakeWord(nextProps.transcript)) {
          abortListening();
        }
      }

Then you can remove isWakeWordFound and these lines from the render method:

{!this.state.isWakeWordFound ? this.checkForWakeword(transcript) : null}
{this.state.isWakeWordFound ? abortListening() : null}