All files / components/TextToSpeech/hooks useSpeechSynthesis.ts

73.33% Statements 77/105
44.23% Branches 23/52
63.15% Functions 12/19
74.75% Lines 77/103

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204        1x 1x 1x 1x         1x 20x 20x 20x 20x   20x 20x 20x 20x 20x     20x   9x     9x 9x 8x         20x 9x 9x 8x           20x   1x   1x 1x     1x 1x                     20x 1x 1x       20x 1x 1x   1x 1x 1x       1x     1x 1x   1x       20x 1x   1x           1x 1x 1x   1x 1x   1x 1x 1x     1x         1x             1x 1x     20x   1x           1x 1x   1x 1x 1x 1x     1x   1x 1x     1x 1x                   20x             20x             20x                 20x 1x 1x     20x                        
import { useState, useEffect, useCallback, useRef } from "react";
import type { SpeechStatus, UseSpeechSynthesisReturn } from "../types";
 
// Chrome 15秒問題への対策: テキストをチャンクに分割
const CHUNK_SIZE = 200;
const DEFAULT_RATE = 1.0;
const MIN_RATE = 0.5;
const MAX_RATE = 2.0;
 
/**
 * Web Speech API (SpeechSynthesis) を管理するカスタムフック
 */
export const useSpeechSynthesis = (): UseSpeechSynthesisReturn => {
  const [status, setStatus] = useState<SpeechStatus>("idle");
  const [rate, setRateState] = useState<number>(DEFAULT_RATE);
  const [isSupported, setIsSupported] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
 
  const utteranceRef = useRef<SpeechSynthesisUtterance | null>(null);
  const chunksRef = useRef<string[]>([]);
  const currentChunkIndexRef = useRef<number>(0);
  const synthRef = useRef<SpeechSynthesis | null>(null);
  const currentLangRef = useRef<string>("ja-JP");
 
  // ブラウザ対応チェック
  useEffect(() => {
    const supported =
      typeof window !== "undefined" &&
      "speechSynthesis" in window &&
      "SpeechSynthesisUtterance" in window;
    setIsSupported(supported);
    if (supported) {
      synthRef.current = window.speechSynthesis;
    }
  }, []);
 
  // ページ遷移時のクリーンアップ
  useEffect(() => {
    return () => {
      if (synthRef.current) {
        synthRef.current.cancel();
      }
    };
  }, []);
 
  // 言語に適した音声を選択
  const selectVoice = useCallback(
    (lang: string): SpeechSynthesisVoice | null => {
      Iif (!synthRef.current) return null;
 
      const voices = synthRef.current.getVoices();
      const langPrefix = lang.split("-")[0]; // 'ja-JP' -> 'ja'
 
      // 優先順位: 完全一致 > プレフィックス一致 > デフォルト
      return (
        voices.find((v) => v.lang === lang) ||
        voices.find((v) => v.lang.startsWith(langPrefix)) ||
        voices.find((v) => v.default) ||
        voices[0] ||
        null
      );
    },
    [],
  );
 
  // テキストを日本語/英語で判定
  const detectLanguage = useCallback((text: string): string => {
    const japaneseRegex = /[\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF]/;
    return japaneseRegex.test(text) ? "ja-JP" : "en-US";
  }, []);
 
  // テキストをチャンクに分割(Chrome 15秒問題対策)
  const splitIntoChunks = useCallback((text: string): string[] => {
    const chunks: string[] = [];
    const sentences = text.split(/([。..!?!?\n]+)/);
 
    let currentChunk = "";
    for (const sentence of sentences) {
      Iif ((currentChunk + sentence).length > CHUNK_SIZE && currentChunk) {
        chunks.push(currentChunk.trim());
        currentChunk = sentence;
      } else {
        currentChunk += sentence;
      }
    }
    Eif (currentChunk.trim()) {
      chunks.push(currentChunk.trim());
    }
    return chunks.length > 0 ? chunks : [text];
  }, []);
 
  // 次のチャンクを読み上げ
  const speakNextChunk = useCallback(() => {
    Iif (!synthRef.current) return;
 
    Iif (currentChunkIndexRef.current >= chunksRef.current.length) {
      setStatus("idle");
      currentChunkIndexRef.current = 0;
      return;
    }
 
    const chunk = chunksRef.current[currentChunkIndexRef.current];
    const utterance = new SpeechSynthesisUtterance(chunk);
    utteranceRef.current = utterance;
 
    utterance.rate = rate;
    utterance.lang = currentLangRef.current;
 
    const voice = selectVoice(currentLangRef.current);
    Eif (voice) {
      utterance.voice = voice;
    }
 
    utterance.onend = () => {
      currentChunkIndexRef.current++;
      speakNextChunk();
    };
 
    utterance.onerror = (event) => {
      if (event.error !== "interrupted" && event.error !== "canceled") {
        setError(`読み上げエラー: ${event.error}`);
        setStatus("idle");
      }
    };
 
    synthRef.current.speak(utterance);
    setStatus("playing");
  }, [rate, selectVoice]);
 
  const speak = useCallback(
    (text: string, lang?: string) => {
      Iif (!synthRef.current || !isSupported) {
        setError("このブラウザは読み上げ機能に対応していません");
        return;
      }
 
      // 既存の読み上げをキャンセル
      synthRef.current.cancel();
      setError(null);
 
      const detectedLang = lang || detectLanguage(text);
      currentLangRef.current = detectedLang;
      chunksRef.current = splitIntoChunks(text);
      currentChunkIndexRef.current = 0;
 
      // 音声リストの読み込みを待つ
      setStatus("loading");
 
      const startSpeaking = () => {
        speakNextChunk();
      };
 
      if (synthRef.current.getVoices().length > 0) {
        startSpeaking();
      } else E{
        synthRef.current.addEventListener("voiceschanged", startSpeaking, {
          once: true,
        });
      }
    },
    [isSupported, detectLanguage, splitIntoChunks, speakNextChunk],
  );
 
  const pause = useCallback(() => {
    if (synthRef.current && status === "playing") {
      synthRef.current.pause();
      setStatus("paused");
    }
  }, [status]);
 
  const resume = useCallback(() => {
    if (synthRef.current && status === "paused") {
      synthRef.current.resume();
      setStatus("playing");
    }
  }, [status]);
 
  const stop = useCallback(() => {
    if (synthRef.current) {
      synthRef.current.cancel();
      chunksRef.current = [];
      currentChunkIndexRef.current = 0;
      setStatus("idle");
    }
  }, []);
 
  const setRate = useCallback((newRate: number) => {
    const clampedRate = Math.max(MIN_RATE, Math.min(MAX_RATE, newRate));
    setRateState(clampedRate);
  }, []);
 
  return {
    status,
    rate,
    isSupported,
    error,
    speak,
    pause,
    resume,
    stop,
    setRate,
  };
};