Skip to content

useSpeech

This hook uses a text speaker with available voices as well as its state and controller methods.

Options

NameTypeDescription
langStringA string representing a BCP 47 language tag.
voiceObjectThe SpeechSynthesisVoice object.
rateNumberThe playback speed (default is 1).
pitchNumberThe pitch at which the utterance will be spoken at (0 to 2) (default is 1).
volumeNumberThe initial volume level (0 to 1) (default is 1).

Return Values

NameTypeDescription
voicesArrayAn array of SpeechSynthesisVoices.
langStringThe language of the current speech synthesis.
voiceObjectThe current selected voice.
rateNumberThe speech rate (speed).
pitchNumberThe speech pitch (intonation).
volumeNumberThe speech volume.
textStringThe text to be spoken.
isSpeakingBooleanIndicates if speech synthesis is in progress.
isPausedBooleanIndicates if speech synthesis is paused.
isEndedBooleanIndicates if speech synthesis has ended.
speakFunctionInitiates speech synthesis with the given text.
togglePlayStateFunctionToggles the play/pause state of speech synthesis. Optional play parameter can force play.
resumeFunctionResumes speech synthesis if paused.
pauseFunctionPauses speech synthesis if playing.
cancelFunctionCancels speech synthesis.
setLangFunctionSets the language for speech synthesis.
setRateFunctionSets the speech rate (speed).
setPitchFunctionSets the speech pitch (intonation).
setVolumeFunctionSets the speech volume.
setVocieFunctionSet a specific voice from the voices.
setCharIndexFunctionSet a specific character index for speech synthesis to start or continue with.

Example Usage

tsx
import { useSpeech } from 'react-pre-hooks';

export default function TextSpeaker() {
  const speech = useSpeech();

  const speak = () => {
    const text = document.querySelector('textarea')?.value;
    if (text) speech.speak(text);
  };

  const selectVocie = e => {
    const index = e.currentTarget.selectedIndex;
    speech.setVoice(speech.voices[index]);
  };

  return (
    <main>
      <div>
        <select onChange={selectVocie}>
          {speech.voices.map(v => (
            <option key={v.name}>{v.name}</option>
          ))}
        </select>
        <button onClick={speak}>Speak</button>
      </div>
      <textarea></textarea>
    </main>
  );
}
import { useSpeech } from 'react-pre-hooks';

export default function TextSpeaker() {
  const speech = useSpeech();

  const speak = () => {
    const text = document.querySelector('textarea')?.value;
    if (text) speech.speak(text);
  };

  const selectVocie = e => {
    const index = e.currentTarget.selectedIndex;
    speech.setVoice(speech.voices[index]);
  };

  return (
    <main>
      <div>
        <select onChange={selectVocie}>
          {speech.voices.map(v => (
            <option key={v.name}>{v.name}</option>
          ))}
        </select>
        <button onClick={speak}>Speak</button>
      </div>
      <textarea></textarea>
    </main>
  );
}

Released under the MIT License.