Skip to content

Androidで長時間オートモード後にTTSが再生されなくなる不具合を修正 - #6235

Merged
TinyKitten merged 4 commits into
devfrom
claude/android-tts-playback-bug-p4fipq
Jun 15, 2026
Merged

TinyKitten merged 4 commits into
devfrom
claude/android-tts-playback-bug-p4fipq

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jun 15, 2026 •

Copy link
Copy Markdown
Member

概要

Android でオートモードなどを使い TTS を長時間再生し続けると、ある時点から音声がアプリ再起動まで一切再生されなくなる不具合を修正します。ネイティブログで AudioTrack init failed / AudioFlinger could not create track, status: -12(NO_MEMORY)を確認し、発話のたびに createAudioPlayer で新規プレイヤー(ExoPlayer/AudioTrack)を生成していたことによるネイティブ音声トラックの枯渇が主因と特定しました。あわせて、音声フェッチのハングで再生パイプラインが固着するデッドロックも修正します。

変更の種類

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

変更内容

  • TTS プレイヤーを発話ごとに生成せず、日本語/英語用の永続インスタンスを replace() で使い回すよう変更し、AudioTrack 枯渇による再生停止を解消(ttsAudioPlayer.ts / useTTS.ts)。ネイティブ解放(remove())はアンマウント時のみに限定。
  • 音声フェッチ(ttsSpeechFetcher.ts)に AbortController ベースのタイムアウト(20 秒)を追加。通信切替やドーズ状態でリクエストが応答もエラーも返さずハングしても、playingRef が固着して以降の TTS が止まるのを防止。timeoutMs は 0・負値・NaN・Infinity が渡されても正の有限値に正規化。
  • playingRef の安全タイムアウトをフェッチ段階から張るよう変更(armPlaybackWatchdog)。トークン取得・フェッチのハングでも再生パイプラインが確実に復帰する。
  • 発話ごとの世代 ID(speechRunIdRef)を導入。各 await の後に世代が進んでいれば継続を破棄し、タイムアウト・新規発話の後に解決の遅れた古いフェッチが stale な音声を割り込ませて再生する事故を防止。
  • プレイヤー再利用により根拠が消滅した日本語→英語間の 100ms 再生ディレイ(EN_PLAYBACK_DELAY_MS)を削除し、日本語の再生完了後すぐ英語を再生。
  • 上記に対応するユニットテストを追加・更新(プレイヤー再利用 / フェッチタイムアウト / timeoutMs 正規化 / ハング復帰 / ストール時はプレイヤーを破棄せず一時停止)。

回帰リスクと対策

  • 影響範囲は TTS 再生パイプラインに限定。音声フォーカス喪失や通信ハングからの復帰用ウォッチドッグ(ストール検知・再生セーフティタイムアウト)は別の失敗ケースの保険として維持しています。
  • 根本原因はネイティブ音声リソースの枯渇のため、最終確認は実機での長時間オートモード(AudioTrack init failed がログに出ず、日本語の直後に英語が続けて再生されること)の検証を推奨します。

テスト

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

関連Issue

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

@github-actions github-actions Bot added the react label Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

ウォークスルー

TTSパイプラインに3つの強化を実施した。ttsSpeechFetcherにAbortControllerを用いたフェッチタイムアウト(TTS_FETCH_TIMEOUT_MS)を追加。ttsAudioPlayerのplayAudioに既存プレイヤー受け取り(player?)を追加し、pause→replace→playで音源差し替え再生を実現。useTTSにarmPlaybackWatchdogを導入し、ハング時の強制リセットとプレイヤー再利用方針によるcleanupAllPlayers/releaseAllPlayersの分離を行った。

変更点

TTSパイプライン強化

レイヤー / ファイル 概要
フェッチタイムアウト制御
src/utils/ttsSpeechFetcher.ts, src/utils/ttsSpeechFetcher.test.ts
TTS_FETCH_TIMEOUT_MS(20秒)定数とFetchSpeechOptions.timeoutMsを追加。fetchSpeechAudio内でAbortControllerを生成し、タイムアウト到達でfetchをabort、finallyでclearTimeout。ハング時にnull返却・signal.abortedを検証するテストを追加。
AudioPlayer再利用(playAudio)
src/utils/ttsAudioPlayer.ts, src/utils/ttsAudioPlayer.test.ts
playAudioのoptionsにplayer?: AudioPlayer | nullを追加。既存プレイヤーがある場合はcreateAudioPlayerを呼ばずpause→replace({uri})→playの順で動作。テストでcreateAudioPlayer未呼び出し・同一インスタンス返却・再生順序を検証。
useTTS: PlayerRef追加とcleanup再設計
src/hooks/useTTS.ts
jaPlayerRef/enPlayerRefをAudioPlayer | null参照として追加。cleanupAllPlayersをリスナー解除+pauseに変更。アンマウント時のみsafeRemovePlayerで破棄するreleaseAllPlayersを新設し、アンマウント処理を切り替え。AudioPlayer型importを追加。
useTTS: armPlaybackWatchdog導入と世代管理
src/hooks/useTTS.ts
PLAYBACK_TIMEOUT_MS基準のarmPlaybackWatchdogを追加。タイムアウト到達時にcleanupAllPlayers+finishPlayingで強制リセット。speechRunIdRefで再生世代を管理し、古い非同期継続の割り込みを抑止。speechWithText開始直後とspeakFromPath冒頭から呼び出し、依存配列にも追加。
useTTS: speakFromPath再生シーケンス刷新とテスト
src/hooks/useTTS.ts, src/hooks/useTTS.test.ts
speakFromPathでplayingRefを即時true化してウォッチドッグを起動。stopEn/stopJaでリスナー解除+pause+参照クリアに統一。JA完了後のEN切り替えからEN_PLAYBACK_DELAY_MS固定ディレイを削除。フェッチ後にisStaleRun()で世代整合性確認するガードを追加。テストにreplaceモック追加、ストールテスト更新、ハング時タイムアウト・2回目replace再利用の新規テストを追加。

シーケンス図

sequenceDiagram
  participant speechWithText
  participant fetchSpeechAudio
  participant armPlaybackWatchdog
  participant speakFromPath
  participant jaPlayer
  participant enPlayer

  rect rgba(100, 149, 237, 0.5)
    Note over speechWithText, armPlaybackWatchdog: フェッチ段階
    speechWithText->>armPlaybackWatchdog: 起動(ハング監視開始)
    speechWithText->>fetchSpeechAudio: timeoutMs付きでフェッチ
    alt フェッチタイムアウト
      fetchSpeechAudio-->>speechWithText: null
      armPlaybackWatchdog-->>speechWithText: finishPlaying(強制リセット)
    else 正常取得
      fetchSpeechAudio-->>speechWithText: AudioBlob
    end
  end
  rect rgba(60, 179, 113, 0.5)
    Note over speakFromPath, enPlayer: 再生段階
    speechWithText->>speakFromPath: jaPath, enPath
    speakFromPath->>jaPlayer: playAudio(jaPlayerRef, replace)
    jaPlayer-->>speakFromPath: onFinish
    speakFromPath->>jaPlayer: stopJa
    speakFromPath->>enPlayer: playAudio(enPlayerRef, replace)
    enPlayer-->>speakFromPath: onFinish
    speakFromPath->>speakFromPath: finishPlaying
  end
Loading

推定コードレビュー工数

🎯 4 (Complex) | ⏱️ ~60 minutes

関連する可能性のあるPR

  • TrainLCD/MobileApp#6163: ttsAudioPlayer.tsのplayAudioおよびuseTTSの再生後処理に同方向の変更が入っており、再生ロック・ウォッチドッグによる復帰・停止ロジックで共通の関心事を持つ。

詩

🐰 うさぎのうた

ハングしても怖くない、ウォッチドッグが見ているよ
プレイヤーは捨てずに、replace でまた歌う
タイムアウトで abort、シグナルを送れ
JA が終わったら EN、ディレイなしで即走れ
🎵 耳をすませば、電車の声が聞こえるよ 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed タイトルは「Androidで長時間オートモード後にTTSが再生されなくなる不具合を修正」と、PR全体の主要な変更(プレイヤーインスタンスの再利用によるAndroid音声トラック枯渇の解決)を正確に要約しており、変更セットの中心的な内容と完全に一致しています。
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.
Description check ✅ Passed PRの説明は概要、変更の種類、変更内容、テスト確認項目、関連Issueを含み、テンプレートの必須セクションをほぼ網羅しており、十分に詳細で適切です。

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 claude/android-tts-playback-bug-p4fipq

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

@TinyKitten TinyKitten self-assigned this Jun 15, 2026

@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: 3

🧹 Nitpick comments (1)
src/utils/ttsAudioPlayer.test.ts (1)

197-202: ⚡ Quick win

pause -> replace -> play の順序も明示的に検証してください

現状は各メソッドの呼び出し有無のみの検証で、順序が崩れてもテストが通る余地があります。順序も固定して回帰を防いでください。

差分案
   expect(mock.player.pause).toHaveBeenCalled();
   expect(mock.player.replace).toHaveBeenCalledWith({
     uri: '/path/to/next.mp3',
   });
   expect(mock.player.play).toHaveBeenCalledTimes(1);
+  const pauseOrder = mock.player.pause.mock.invocationCallOrder[0];
+  const replaceOrder = mock.player.replace.mock.invocationCallOrder[0];
+  const playOrder = mock.player.play.mock.invocationCallOrder[0];
+  expect(pauseOrder).toBeLessThan(replaceOrder);
+  expect(replaceOrder).toBeLessThan(playOrder);

As per coding guidelines, Test agents in isolation and with integration tests to ensure correctness and compatibility を満たすため、順序の明示検証が有効です。

🤖 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/ttsAudioPlayer.test.ts` around lines 197 - 202, The test for the
pause-replace-play sequence currently only verifies that each method on
mock.player is called individually, without ensuring they are called in the
correct order. To fix this, add explicit order verification to the test by
checking the sequence of calls on mock.player. Verify that pause is called
first, then replace, and then play last, so that any regression in the call
order will be caught by the test. Use Jest's call tracking capabilities to
enforce this ordering constraint alongside the existing call validation checks.

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.test.ts`:
- Around line 393-451: The test does not properly isolate the second TTS
utterance fetch from the initial render's fetch and prefetch operations. The
default useTTSText mock returns a nextText array, causing both a regular fetch
and a prefetch on the first render, so the mockFetch.toHaveBeenCalledTimes(2)
expectation may pass before the second rerender actually completes. Fix this by
either initializing the useTTSText mock to return nextText: [] from the start
(so only one fetch happens initially), or by capturing the fetch call count
before the rerender and then waiting for it to increment by 1 specifically for
the second utterance. This ensures the mockPlayer.replace verification truly
tests the reuse behavior triggered by the second speech text change.

In `@src/hooks/useTTS.ts`:
- Around line 157-168: Race condition exists where old Promise resolutions from
fetch operations can still execute and replay stale audio even after timeout or
new utterances begin. Introduce a generation or run id that is incremented for
each new utterance request. In the armPlaybackWatchdog function (lines 157-168),
store the current generation id before cleanup so that subsequent
timeout-triggered cleanup invalidates pending operations. In the fetch/Promise
handling code (lines 284-311), before executing any callbacks like
speechWithText or finishPlaying, verify that the generation id stored when the
request was initiated still matches the current generation id. If it does not
match, skip executing the callback to discard old async continuations and
prevent stale audio playback from interrupting newly started utterances or after
timeouts.

In `@src/utils/ttsSpeechFetcher.ts`:
- Around line 126-127: The timeoutMs parameter destructuring in the
ttsSpeechFetcher function does not validate that the value is a positive finite
number. When 0, negative values, NaN, or Infinity are explicitly passed as
timeoutMs, they bypass the default value assignment and are later used directly
in the setTimeout call at line 152, breaking the timeout protection mechanism.
Add validation logic after the options destructuring to normalize timeoutMs to a
positive finite value, ensuring it falls within acceptable bounds before it is
used in the setTimeout call.

---

Nitpick comments:
In `@src/utils/ttsAudioPlayer.test.ts`:
- Around line 197-202: The test for the pause-replace-play sequence currently
only verifies that each method on mock.player is called individually, without
ensuring they are called in the correct order. To fix this, add explicit order
verification to the test by checking the sequence of calls on mock.player.
Verify that pause is called first, then replace, and then play last, so that any
regression in the call order will be caught by the test. Use Jest's call
tracking capabilities to enforce this ordering constraint alongside the existing
call validation checks.
🪄 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: 1e239d93-3f39-45dd-a931-269a796cfa80

📥 Commits

Reviewing files that changed from the base of the PR and between 9457d1c and db99685.

📒 Files selected for processing (6)
  • src/hooks/useTTS.test.ts
  • src/hooks/useTTS.ts
  • src/utils/ttsAudioPlayer.test.ts
  • src/utils/ttsAudioPlayer.ts
  • src/utils/ttsSpeechFetcher.test.ts
  • src/utils/ttsSpeechFetcher.ts

Comment thread src/hooks/useTTS.test.ts Resolved
Comment thread src/hooks/useTTS.ts Resolved
Comment thread src/utils/ttsSpeechFetcher.ts Resolved
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.

2 participants