typescriptintermediate

useSpeechSynthesis Hook

Text-to-speech hook using the Web Speech API with voice selection, rate, and pitch control.

typescript
import { useState, useEffect, useCallback } from 'react';

export function useSpeechSynthesis() {
  const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([]);
  const [speaking, setSpeaking] = useState(false);

  useEffect(() => {
    const loadVoices = () => setVoices(speechSynthesis.getVoices());
    loadVoices();
    speechSynthesis.onvoiceschanged = loadVoices;
    return () => { speechSynthesis.onvoiceschanged = null; };
  }, []);

  const speak = useCallback((text: string, options?: {
    voice?: SpeechSynthesisVoice;
    rate?: number;
    pitch?: number;
  }) => {
    const utterance = new SpeechSynthesisUtterance(text);
    if (options?.voice) utterance.voice = options.voice;
    utterance.rate = options?.rate ?? 1;
    utterance.pitch = options?.pitch ?? 1;
    utterance.onstart = () => setSpeaking(true);
    utterance.onend = () => setSpeaking(false);
    speechSynthesis.speak(utterance);
  }, []);

  const stop = useCallback(() => {
    speechSynthesis.cancel();
    setSpeaking(false);
  }, []);

  return { voices, speaking, speak, stop };
}

Use Cases

  • Accessibility features
  • Voice assistants

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.