voice icon indicating copy to clipboard operation
voice copied to clipboard

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

Open codding123vbf opened this issue 1 year ago • 0 comments

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;

codding123vbf avatar Feb 15 '24 13:02 codding123vbf