Search code examples
reactjstext-to-speech

Web Speech API for reading individual characters


I have tried react-speech-kit but my requirement is reading individual characters. I explored Web Speech API but couldn't find anything. If anyone knows any alternatives much appreciated. Thanks.


Solution

  • You can use tts-react and just split the string before asking it to speak.

    import { useTts } from 'tts-react'
    
    const SpeakCharacters = (text = '') => {
      const { ttsChildren } = useTts({
        children: text.split(''),
        autoPlay: true,
        markTextAsSpoken: true
      })
    
      return (
        <>{ttsChildren}</>
      )
    }
    
    const App = () => {
      return <SpeakCharacters text="Speak these characters on render." />
    }
    

    If you want to speak the characters more slowly then you can do this:

    const SpeakCharacters = (text = '') => {
      const { ttsChildren, set, play } = useTts({
        children: text.split(''),
        markTextAsSpoken: true
      })
    
      useEffect(() => {
        set.rate(0.7)
        play()
      }, [set, play])
    
      return <>{ttsChildren}</>
    }