javascriptreact-nativeexpotext-to-speechtouchableopacity

react native TouchableOpacity, different functions by first and second click


I'm creating a simple text-to-speech function for my react native app. I have a button, when you click it for the first time, it will read the text and play the sound. But I want to make it dynamic. For example: If you click again it should stop, if click again, should play again, etc..... But now, it is only available for playing the sound with any click. Where/how should I execute the stopReadText()? I still don't have any idea about this. Thanks a lot.

Here is the code:

const readText = () => {
    Speech.speak('text')
  }

const stopReadText = () => {
    Speech.stop()
  }

  return (
    <View>
      <TouchableOpacity onPress=(readText)>
        <Divider style={styles.modalDivider} />
        <Image
          style={styles.speaker}
          source={require('../../assets/speaker.png')}
        />
      </TouchableOpacity>
    </View>
  )

(I am using expo-speech)


Solution

  • You can do it by taking on a boolean state variable:

    import { useState } from 'react';
    
    const [isPlay,setIsPlay]=useState(false)
    
    const readText = () => {
        Speech.speak('text')
      }
    
    const stopReadText = () => {
        Speech.stop()
      }
    
    const handlePlay =() =>{
      if(!setIsPlay){
          readText()
          setIsPlay(true)
      }
      else {
          stopReadText()
          setIsPlay(false)
      }
    
     }
    
    
      return (
        <View>
          <TouchableOpacity onPress={handlePlay}>
            <Divider style={styles.modalDivider} />
            <Image
              style={styles.speaker}
              source={require('../../assets/speaker.png')}
            />
          </TouchableOpacity>
        </View>
      )