react-native-voice / voice

:microphone: React Native Voice Recognition library for iOS and Android (Online and Offline Support)
MIT License
1.81k stars 488 forks source link

temporary fix for recognition stop after a short delay...now the recognition will not be stopped until the user press the stop button...here is my code #480

Open codding123vbf opened 7 months ago

codding123vbf commented 7 months ago

import React, { useEffect, useRef, useState } from 'react'; import { View, Text, TouchableOpacity, Button, Platform, PermissionsAndroid, ScrollView, } from 'react-native'; import Voice from '@react-native-voice/voice';

const SpeechText = () => {

const [started, setstarted] = useState('')
const [ended, setended] = useState('')
const [results, setresults] = useState([])
const [intervalId, setintervalId] = useState(null)

useEffect(() => {

    Voice.onSpeechStart = onSpeechStart
    Voice.onSpeechEnd = onSpeechEnd
    Voice.onSpeechResults = onSpeechResults

    return () => {
        Voice.destroy().then(Voice.removeAllListeners)
    }

}, [])

const onSpeechStart = async (e) => {
    console.log(e)
    setstarted('true')
}

const onSpeechEnd = async (e) => {
    console.log(e)
    setended('true')
}

const onSpeechResults = async (e) => {
    console.log(e)
    setresults(prevMedia => [...prevMedia, ' ' + e.value])
    startRecognizing()
    const id = setInterval(() => {
        startRecognizing()
        console.log('after 5 seconds')
    }, 5000)
    setintervalId(id)
}

const stopInterval = () => {
    if (intervalId !== null) {
        clearInterval(intervalId)
        setintervalId(null)
    }
}

useEffect(() => {
    return () => {
        if (intervalId != null) {
            clearInterval(intervalId)
        }
    }
}, [intervalId])

const startRecognizing = async () => {

    try {
        await Voice.start('en-US')
        setstarted('')
        setended('')
        // setresults([])

    } catch (error) {
        console.log(error, 'error after pressing start button')
    }
}

const stopRecognizing = async () => {

    try {
        await Voice.stop()
        setstarted('')
        setended('')
        setresults([])
    } catch (error) {
        console.log(error, 'error after pressing stop button')
    }
}

return (
    <View style={{ flex: 1, backgroundColor: 'white', justifyContent: 'center', alignItems: 'center' }}>

        <Button title='recording start' onPress={() => {
            startRecognizing()
        }} />

        <Button title='recording stop' onPress={() => {
            stopInterval();
            stopRecognizing();
        }} />
        <Text style={{ color: "black", fontSize: 20 }}>{results}</Text>

    </View>
);

};

export default SpeechText;