Skip to content

Androidでexpo-audioからエラーイベントがJSへ届かずTTS再生パイプラインが長時間ロックされる問題をストール検知ウォッチドッグで修正 - #6163

Merged
TinyKitten merged 2 commits into
devfrom
claude/android-tts-playback-c21pi0
Jun 10, 2026

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

概要

Android版でTTSがとあるタイミングで全く再生されなくなる問題の調査と修正。

expo-audio 55.0.13のAndroidネイティブ実装(AudioPlayer.kt)にはPlayer.Listener#onPlayerErrorが実装されておらず、ExoPlayerが再生エラーで停止してもJSへはerrorイベントもdidJustFinishも届かない。また音声フォーカスの恒久喪失(AUDIOFOCUS_LOSS)時は全プレイヤーが無通知でpauseされ自動復帰しない。この状態に陥るとuseTTSのplayingRefが300秒のセーフティタイムアウトまでロックされ、その間のアナウンスはすべて握り潰される(=他アプリの音声再生・フォーカス喪失・再生エラー直後にTTSが全く再生されない症状と一致)。

playAudioに再生位置ポーリングによるストール検知ウォッチドッグを追加し、ネイティブからイベントが届かなくても約10秒で打ち切って次のアナウンスへ復帰できるようにした。

変更の種類

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

変更内容

  • src/utils/ttsAudioPlayer.ts: playAudioに1秒間隔のストール検知ウォッチドッグを追加。player.playingとplayer.currentTimeをポーリングし、再生位置が10秒間進まなければonErrorで打ち切って再生パイプラインを解放する。完了・エラー・破棄時の二重発火はsettledフラグで防止し、リスナー解除と同時にウォッチドッグも確実に停止する
  • src/hooks/useTTS.ts: 日本語再生完了後にsetTimeout内で英語プレイヤーを生成する箇所をtry/catchで保護(コールバック内の例外は誰もキャッチせずplayingRefがロックされたままになるため)。PLAYBACK_TIMEOUT_MSのコメントを実態(最終フォールバック)に合わせて更新
  • src/utils/ttsAudioPlayer.test.ts / src/hooks/useTTS.test.ts: ストール検知・再生進行中の誤検知防止・完了/解除後のウォッチドッグ停止・ストールからの復帰シナリオのテストを追加

テスト

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

関連Issue

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


Generated by Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • TTS再生開始でのエラー時に確実に後片付けと終了処理が行われるようになりました。
    • 再生が進まない(ストール)状態を検知し、警告ログ出力のうえ対象プレイヤーを停止/削除して復帰を図ります。
    • 状態リスナーと監視タイマーの解除処理を一元化しました。
  • Tests

    • ストール検知や復帰、タイマー制御、各種例外挙動を含むテストを大幅に拡充しました。

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

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f428a0d7-6732-4ebc-83af-f6f335eacba4

📥 Commits

Reviewing files that changed from the base of the PR and between bfdef9a and e3f0406.

📒 Files selected for processing (1)
  • src/utils/ttsAudioPlayer.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/ttsAudioPlayer.test.ts

📝 Walkthrough

ウォークスルー

Android ネイティブオーディオで didJustFinish/error 未到来の停止を setInterval ポーリングで検知し、stalled 時に onError('Playback stalled') を返すウォッチドッグを追加。playAudio のコールバック統合と listener/remove の監視解除を一貫化。useTTS の EN プレイヤー生成時の例外処理と関連テストを拡張。

チェンジ

TTS 再生ストール検知メカニズム

Layer / File(s) Summary
ストール検知定数と公開インターフェース定義
src/utils/ttsAudioPlayer.ts
STALL_TIMEOUT_MS(10_000)とSTALL_CHECK_INTERVAL_MS(1_000)をエクスポート。
ストール検知ウォッチドッグ実装と監視流制御
src/utils/ttsAudioPlayer.ts
playAudio に settled フラグ、settle 統合、stalledTicks/lastCurrentTime、setInterval ポーリング監視を追加。一定期間 player.playing/currentTime が変化しなければ onError(new Error('Playback stalled')) を settle 経由で呼ぶ。listener.remove は監視停止(clearInterval)とリスナー削除を確実に行う。
ttsAudioPlayer テストと mock プレイヤー拡張
src/utils/ttsAudioPlayer.test.ts
テストが STALL_CHECK_INTERVAL_MS/STALL_TIMEOUT_MS を参照。createMockPlayer が playing 初期値を受け取るように変更。jest.useFakeTimers() を用い、ストール時の onError、playing=true 時の非ストール扱い、currentTime 更新中の非ストール扱い、再生完了後や listener.remove() 後の監視停止、playing 参照例外時の復帰などのテストを追加。
useTTS エラーハンドリング改善とコメント更新
src/hooks/useTTS.ts
EN プレイヤー生成の setTimeout コールバック内で playAudio を try/catch でラップし、例外時に enCleanup を実行して finishPlaying に到達させるように変更。PLAYBACK_TIMEOUT_MS コメントを更新。
useTTS テスト mock 更新とストール検知テスト追加
src/hooks/useTTS.test.ts
createMockPlayer を playing オプションで拡張し、再生安全タイムアウト系テストで playing=true を再現。ストール復帰テストを追加して、タイムアウト到達時の console.warn 出力と対象プレイヤーの pause/remove が呼ばれることを検証。

シーケンスダイアグラム

sequenceDiagram
  participant Caller as 呼び出し元 (useTTS等)
  participant PlayAudio as playAudio (ウォッチドッグ)
  participant Player as player (Expo.Audio)
  participant Settle as settle (コールバック統合)

  Caller->>PlayAudio: playAudio(player, onFinish, onError)
  PlayAudio->>Player: player.play()
  PlayAudio->>Player: playbackStatusUpdate リスナー登録
  PlayAudio->>PlayAudio: setInterval 開始 (player.playing/currentTime 監視)
  Note over PlayAudio: ストール監視ループ開始

  alt 正常にイベント受信
    Player->>PlayAudio: didJustFinish / error
    PlayAudio->>Settle: settle() -> onFinish/onError
  else ストール検知
    PlayAudio->>PlayAudio: stalledTicks 増加 -> max 到達
    PlayAudio->>Settle: settle(new Error('Playback stalled'))
  end

  Settle->>PlayAudio: clearInterval 停止
  Settle->>Player: listener.remove()
  Settle->>Caller: onFinish / onError 実行
Loading

推定コード レビュー時間

🎯 3 (Moderate) | ⏱️ ~25 分

提案ラベル

react

ポエム

🐰 滞る音の隙間に目を凝らし、
setInterval が静けさを数え、
ひとつの settle で幕を閉じる、
小さな時計が再生を救うよ。

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed タイトルは、Android版でTTS再生パイプラインが長時間ロックされる問題をストール検知ウォッチドッグで修正するという、プルリクエストの主要な変更内容を正確に表現しており、明確で具体的である。
Description check ✅ Passed テンプレートに定義された全ての主要セクション(概要、変更の種類、変更内容、テスト)が記述されており、各セクションに適切な情報が含まれている。バグ修正であることが明記されており、具体的な技術的詳細も充実している。
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.

✏️ 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-c21pi0

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

@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.

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

181-200: 💤 Low value

console.warn spy の検証を追加することを検討してください

warnSpy を設定していますが、実際にストール時の警告メッセージが出力されたかの検証がありません。ストール検知のログ出力も意図した動作の一部であれば、アサーションを追加するとテストの信頼性が向上します。

♻️ 提案する修正
     jest.advanceTimersByTime(STALL_TIMEOUT_MS + STALL_CHECK_INTERVAL_MS);

     expect(onError).toHaveBeenCalledTimes(1);
     expect(onError).toHaveBeenCalledWith(expect.any(Error));
     expect(onFinish).not.toHaveBeenCalled();
     expect(mock.listenerRemove).toHaveBeenCalledTimes(1);
+    expect(warnSpy).toHaveBeenCalledWith(
+      '[ttsAudioPlayer] playback stalled, aborting:',
+      'stalled.mp3'
+    );

     warnSpy.mockRestore();
🤖 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 181 - 200, The test sets a
console.warn spy (warnSpy) but never asserts it was called; update the test for
the stalled-play scenario to assert that console.warn was invoked with the
expected warning when playAudio detects a stall: after advancing timers (using
STALL_TIMEOUT_MS and STALL_CHECK_INTERVAL_MS) add assertions that warnSpy was
called (e.g., toHaveBeenCalledTimes(1)) and that it was called with a message or
pattern indicating a stall (use expect.any(String) or a substring match),
keeping the existing assertions for onError/onFinish and listener removal;
reference the mock setup via createMockPlayer/mockCreateAudioPlayer and the
playAudio call to locate the test.
🤖 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.

Nitpick comments:
In `@src/utils/ttsAudioPlayer.test.ts`:
- Around line 181-200: The test sets a console.warn spy (warnSpy) but never
asserts it was called; update the test for the stalled-play scenario to assert
that console.warn was invoked with the expected warning when playAudio detects a
stall: after advancing timers (using STALL_TIMEOUT_MS and
STALL_CHECK_INTERVAL_MS) add assertions that warnSpy was called (e.g.,
toHaveBeenCalledTimes(1)) and that it was called with a message or pattern
indicating a stall (use expect.any(String) or a substring match), keeping the
existing assertions for onError/onFinish and listener removal; reference the
mock setup via createMockPlayer/mockCreateAudioPlayer and the playAudio call to
locate the test.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f2b79888-5165-43ff-bbce-fa4c87ec1d0e

📥 Commits

Reviewing files that changed from the base of the PR and between 178fcd6 and bfdef9a.

📒 Files selected for processing (4)
  • src/hooks/useTTS.test.ts
  • src/hooks/useTTS.ts
  • src/utils/ttsAudioPlayer.test.ts
  • src/utils/ttsAudioPlayer.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.

2 participants