Skip to content

ネイティブTTSの音質向上とAndroidで英語が日本語音声で合成される問題の修正 - #6457

Merged
TinyKitten merged 8 commits into
devfrom
feature/native-tts-voice-quality
Jul 23, 2026
Merged

TinyKitten merged 8 commits into
devfrom
feature/native-tts-voice-quality

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jul 23, 2026 •

Copy link
Copy Markdown
Member

概要

OS ネイティブ TTS(expo-speech)の読み上げで、端末にインストール済みの最高品質音声(Premium / Enhanced)を自動選択するようにし、音質を可能な範囲で引き上げました。あわせて、Android で英語アナウンスが日本語音声で合成される問題を修正しました。実機調査の結果、真の根本原因は英語文への日本語表記の混入(<phoneme> タグの表記テキストが日本語の駅データ)で、TTS エンジンが言語を誤判定していたことでした。TTS 設定画面への高品質音声の案内文追加、注意文言の更新も含みます。

変更の種類

  • バグ修正
  • 新機能
  • リファクタリング
  • ドキュメント
  • CI/CD
  • その他

変更内容

Android で英語が日本語音声で合成される問題の修正(根本原因)

  • 原因: 旧外部 TTS API(Azure)向けに生成される <phoneme alphabet="ipa" ph="...">表記</phoneme> は IPA 発音(ph 属性)が読まれ表記テキストは無視されていたが、ネイティブ TTS は IPA を解釈できないため表記テキストがそのまま読まれる。駅データによっては表記が日本語(例: surface が「あかさか」で fallbackText 未設定)のため、英語文が "Arriving at あかさか K 7." となり、voice を明示指定していても TTS エンジンが言語を誤判定して日本語音声で合成されていた
  • 修正: wrapPhoneme で、セグメントから組み立てた可視テキストに日本語文字(ひらがな・カタカナ・CJK 漢字・半角カナ)が含まれる場合はセグメントを使わずローマ字名(nameRoman 等の fallback)全体へフォールバックする。駅名・路線名・直通先など nameTtsSegments を使う全箇所に効く

音質向上(音声の自動選択)

  • nativeTtsVoice ユーティリティを新設。Speech.getAvailableVoicesAsync() の結果から言語ごとに Premium > Enhanced > その他の優先順で音声を選び、useTTS が Speech.speak() に voice を明示指定する
  • expo-speech の iOS 実装は AVSpeechSynthesisVoiceQuality.premium を "Default" として報告するため、quality フィールドに加えて音声識別子(com.apple.voice.premium.* 等)でも品質を判定して補完
  • iOS では Premium / Enhanced が見つからない場合は voice 未指定のままにし、ユーザーが OS 設定で選んだ既定音声を尊重
  • Android では言語選択の正しさのためにも音声を明示指定する(既定品質のローカル音声も対象、allowDefaultQuality)。地域一致(en-US)が無ければ同一言語の別地域(en-GB 等)、ローカル優先でネットワーク必須音声は最後の手段、対象言語の音声が皆無ならその言語の発話をスキップ

発話パイプラインの堅牢化

  • JA→EN は OS の読み上げキューへ一括投入する。Android の TextToSpeech#speak() は呼び出し時点の言語・音声設定を発話リクエストごとにスナップショットし、iOS の AVSpeechUtterance も発話単位で音声を保持するため、発話ごとに異なる音声を安全に指定できる。エンジンが前の発話の再生中に次の合成を先行できるため、JA→EN 間の無音(合成待ちのラグ)が最小化される
  • 発話開始前に音声選択の完了を待つよう変更(上限 5 秒)。初回アナウンスが voice 未指定で合成されるレースを解消
  • expo-speech の Android 実装を patch-package で修正(patches/expo-speech+55.0.16.patch): voice 指定時は setVoice を最優先で適用し setLanguage との競合を排除。voice が見つからない場合は Locale.forLanguageTag による正しい BCP 47 解釈と言語のみ Locale への段階的フォールバックで解決(Locale(String) に地域付きタグを渡すと不正 Locale となり端末既定言語で合成される不備への対処)。音声一覧の取得失敗時など voice 未指定で発話する稀な経路の保険として維持

その他

  • TTS 設定画面に高品質音声の案内文を追加(iOS: 「設定 > アクセシビリティ > 読み上げコンテンツ > 声」からのダウンロード案内 / Android: 音声データ更新の案内)
  • ttsAlertText の「インターネット未接続状態では動作しません」という文言を、ネイティブ TTS の実態に合わせて更新
  • 単体テスト追加: nativeTtsVoice 19 件、wrapPhoneme の日本語表記フォールバック 13 件、useTTS の音声指定・一括キュー・音声選択完了待ち・発話スキップ

テスト

  • npm run lint が通ること
  • npm test が通ること
  • npm run typecheck が通ること

npm run lint / npm run typecheck / npm test(193 スイート / 2070 件)すべてパス。日本語設定の Android 実機で、NEXT / ARRIVING 両方の英語アナウンスが英語音声で読まれることを確認済み(従来 "Arriving at あかさか K 7." と日本語混入していた駅で検証)。

留意点:

  • native パッチを含むため Android の再ビルドが必要です(npm install で patch-package が適用されます)
  • 実際の音質向上は端末に Premium / Enhanced 音声がダウンロード済みかに依存するため、iOS 実機での聴き比べも推奨します

関連Issue

スクリーンショット(任意)

Summary by CodeRabbit

  • 新機能
    • iOS・Androidで、端末に最適な音声品質の読み上げボイスを自動選択するようになりました。
    • 利用できない言語の読み上げを適切にスキップし、音声再生の安定性を向上しました。
    • TTS設定画面に、OS別の音声品質に関する案内を追加しました。
  • 改善
    • 日本語を含む文章の読み上げ時に、より自然なフォールバック処理を行うようになりました。
    • 音声再生が完了しない場合でも、処理が安全に終了するよう改善しました。

@TinyKitten TinyKitten self-assigned this Jul 23, 2026
@github-actions github-actions Bot added the react label Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • ✅ Review completed - (🔄 Check again to review again)
📝 Walkthrough

Walkthrough

端末のTTS音声を言語別に選択し、useTTS の逐次読み上げへ適用する処理を追加しました。Android側の音声適用とフォールバックも更新し、設定画面にはOS別の音声品質案内を表示します。

Changes

ネイティブTTS音声対応

Layer / File(s) Summary
音声品質判定と選択
src/utils/nativeTtsVoice.ts, src/utils/nativeTtsVoice.test.ts
言語タグ、品質、地域一致、ローカル音声を考慮して音声識別子を選択し、選択規則をテストします。
逐次読み上げへの音声適用
src/hooks/useTTS.ts, src/hooks/useTTS.test.ts, patches/expo-speech+55.0.16.patch
利用可能な音声を取得し、日本語・英語の音声指定、対象音声がない言語のスキップ、コールバックに基づくキュー進行を実装・検証します。Android側ではボイス優先と言語フォールバック、診断ログを追加します。
音声品質案内の表示
src/screens/TTSSettings.tsx, assets/translations/en.json, assets/translations/ja.json
TTS設定画面にiOS・Android別の音声品質案内を追加し、既存の注意文を更新します。

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Poem

端末の声をぴょんと選び、
日本語英語、順に響く。
AndroidもiOSも案内を添え、
うさぎは耳を澄ませます。

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed 主変更であるネイティブTTSの音質自動選択とAndroidの誤音声問題修正を要約しており、変更内容と一致しています。
Description check ✅ Passed 概要・変更の種類・変更内容・テストが揃っており、テンプレートの必須要素を十分満たしています。
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/native-tts-voice-quality

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/screens/TTSSettings.tsx (1)

150-162: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

src/screens/TTSSettings.test.tsx に iOS / Android の分岐テストを追加してください
Platform.OS で ttsVoiceQualityNoticeIOS / ttsVoiceQualityNoticeAndroid が切り替わるため、両ケースで正しい翻訳キーが描画されることを確認したいです。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/screens/TTSSettings.tsx` around lines 150 - 162,
src/screens/TTSSettings.test.tsx に、Platform.OS が iOS の場合は
ttsVoiceQualityNoticeIOS、Android の場合は ttsVoiceQualityNoticeAndroid が translate
に渡されて描画されることを検証する分岐テストを追加してください。既存の TTSSettings テスト構成と Platform
のモック方法を再利用し、両ケースを確認してください。

Source: Coding guidelines

src/utils/nativeTtsVoice.test.ts (1)

11-46: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

テスト後にモック状態をリセットしてください。

この .test.ts には afterEach(() => jest.clearAllMocks()) がありません。将来のモック追加時もテスト間の状態漏れを防ぐため、スイートに追加してください。
As per coding guidelines, afterEach では jest.clearAllMocks() を呼び出すこと。

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/nativeTtsVoice.test.ts` around lines 11 - 46, scoreVoiceQuality
テストスイートに afterEach フックを追加し、各テスト後に jest.clearAllMocks() を呼び出してモック状態をリセットしてください。

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/hooks/useTTS.ts`:
- Around line 83-106: Update the useTTS initialization and first Speech.speak
flow so the initial utterance waits for getAvailableVoicesAsync to finish, or
explicitly uses the default voice when voice IDs remain unavailable. Ensure
jaVoiceIdRef and enVoiceIdRef are not assumed initialized before the
asynchronous voice-loading effect completes.

---

Nitpick comments:
In `@src/screens/TTSSettings.tsx`:
- Around line 150-162: src/screens/TTSSettings.test.tsx に、Platform.OS が iOS の場合は
ttsVoiceQualityNoticeIOS、Android の場合は ttsVoiceQualityNoticeAndroid が translate
に渡されて描画されることを検証する分岐テストを追加してください。既存の TTSSettings テスト構成と Platform
のモック方法を再利用し、両ケースを確認してください。

In `@src/utils/nativeTtsVoice.test.ts`:
- Around line 11-46: scoreVoiceQuality テストスイートに afterEach フックを追加し、各テスト後に
jest.clearAllMocks() を呼び出してモック状態をリセットしてください。
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e37ac1f8-16c1-427a-baf7-9cba3033d309

📥 Commits

Reviewing files that changed from the base of the PR and between 946513e and 6d3fd03.

📒 Files selected for processing (7)
  • assets/translations/en.json
  • assets/translations/ja.json
  • src/hooks/useTTS.test.ts
  • src/hooks/useTTS.ts
  • src/screens/TTSSettings.tsx
  • src/utils/nativeTtsVoice.test.ts
  • src/utils/nativeTtsVoice.ts

Comment thread src/hooks/useTTS.ts Resolved
@TinyKitten TinyKitten changed the title 端末の最高品質音声(premium/enhanced)を自動選択してネイティブTTSの音質を向上 ネイティブTTSの音質向上とAndroidで英語が日本語音声で合成される問題の修正 Jul 23, 2026
TinyKitten and others added 6 commits July 23, 2026 11:21

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/hooks/useTTS.ts (1)

119-131: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

voices.length > 0 条件により androidVoicesLoadedRef が永久に false のままになりうる。

getAvailableVoicesAsync() が例外を投げずに空配列を返した場合(端末側の一時的な不具合など)、androidVoicesLoadedRef.current は true にならず、canSpeakJa/canSpeakEn は「不明なら発話許可」にフォールバックします。結果として音声未検出時のスキップ判定が機能せず、本PRが修正対象とする「英語が日本語音声で読まれる」問題が再発する余地があります。

🐛 Proposed fix
-        if (Platform.OS === 'android' && voices.length > 0) {
-          androidVoicesLoadedRef.current = true;
+        if (Platform.OS === 'android') {
+          androidVoicesLoadedRef.current = true;
           if (!jaVoiceIdRef.current) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useTTS.ts` around lines 119 - 131, Update the Android voice-loading
logic in the useTTS hook so androidVoicesLoadedRef.current becomes true whenever
getAvailableVoicesAsync completes successfully, including when voices is an
empty array. Keep the existing voice-specific warnings and ensure
canSpeakJa/canSpeakEn treat the completed empty result as unavailable rather
than falling back to allowing speech.
🧹 Nitpick comments (1)
src/hooks/useTTS.ts (1)

304-334: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Speech.speak() 呼び出しを try/catch で保護してください。

ループ内でSpeech.speakが同期的に例外を投げた場合、settle()が呼ばれずremainingが0に到達しないため、playingRef.currentはarmPlaybackWatchdogのタイムアウト(PLAYBACK_TIMEOUT_MS)まで解放されません。ファイル内の他箇所(Speech.stop())ではtry/catchで防御している一貫したスタイルがあるので、揃えることを推奨します。

🛡️ Proposed fix
         for (const utterance of utterances) {
-          Speech.speak(utterance.text, {
-            language: utterance.language,
-            ...(utterance.voice ? { voice: utterance.voice } : {}),
-            onDone: settle,
-            onStopped: settle,
-            onError: (error) => {
-              console.warn('[useTTS] speech error:', error);
-              settle();
-            },
-          });
+          try {
+            Speech.speak(utterance.text, {
+              language: utterance.language,
+              ...(utterance.voice ? { voice: utterance.voice } : {}),
+              onDone: settle,
+              onStopped: settle,
+              onError: (error) => {
+                console.warn('[useTTS] speech error:', error);
+                settle();
+              },
+            });
+          } catch (e) {
+            console.warn('[useTTS] Speech.speak failed:', e);
+            settle();
+          }
         }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/hooks/useTTS.ts` around lines 304 - 334,
ループ内のSpeech.speak呼び出しをtry/catchで保護し、同期例外が発生した場合も既存のsettle()を必ず呼び出してremainingを減算し、再生状態を解放できるようにしてください。既存のonErrorログ・コールバック処理と、ファイル内のSpeech.stop()にある防御的な例外処理のスタイルを維持してください。
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/hooks/useTTS.ts`:
- Around line 119-131: Update the Android voice-loading logic in the useTTS hook
so androidVoicesLoadedRef.current becomes true whenever getAvailableVoicesAsync
completes successfully, including when voices is an empty array. Keep the
existing voice-specific warnings and ensure canSpeakJa/canSpeakEn treat the
completed empty result as unavailable rather than falling back to allowing
speech.

---

Nitpick comments:
In `@src/hooks/useTTS.ts`:
- Around line 304-334:
ループ内のSpeech.speak呼び出しをtry/catchで保護し、同期例外が発生した場合も既存のsettle()を必ず呼び出してremainingを減算し、再生状態を解放できるようにしてください。既存のonErrorログ・コールバック処理と、ファイル内のSpeech.stop()にある防御的な例外処理のスタイルを維持してください。

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9545c9a6-072c-4ce4-8cdd-9181b8e27e63

📥 Commits

Reviewing files that changed from the base of the PR and between c9e05b2 and b47e426.

📒 Files selected for processing (5)
  • patches/expo-speech+55.0.16.patch
  • src/hooks/useTTS.test.ts
  • src/hooks/useTTS.ts
  • src/utils/phoneme.test.ts
  • src/utils/phoneme.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/hooks/useTTS.test.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant