Repository navigation
TTS処理の純粋関数化 - #5134
TTS処理の純粋関数化#5134
Conversation
📝 WalkthroughWalkthroughAndroid の位置更新後にバックグラウンドTTSを起動する呼び出しを追加し、Expo依存の音声処理を廃止して TTSPlayer シングルトンおよび新しい TTS テキスト生成 / ヘルパー群へ置き換える大規模リファクタを導入。 Changes
Sequence Diagram(s)sequenceDiagram
participant App as アプリ
participant LocationTask as 位置更新タスク
participant BGTrigger as backgroundTTSTrigger
participant State as アプリ状態(station/line/navigation/theme)
participant TTSPlayer as TTSPlayer
participant TTSAPI as TTS API
participant ExpoAudio as ExpoAudio
App->>LocationTask: setLocation(位置更新)
LocationTask->>BGTrigger: triggerBackgroundTTS()
BGTrigger->>State: 状態取得(station/line/navigation/theme)
BGTrigger->>BGTrigger: データ検証・TTSテキスト生成 (generateTTSText)
BGTrigger->>TTSPlayer: setAudioMode(backgroundEnabled: true)
BGTrigger->>TTSPlayer: speak(textJa, textEn)
alt キャッシュヒット
TTSPlayer->>TTSPlayer: ローカルキャッシュから読み込み
else キャッシュミス
TTSPlayer->>TTSAPI: fetchSpeech(text, idToken)
TTSAPI-->>TTSPlayer: base64 音声データ
TTSPlayer->>TTSPlayer: ファイル保存・キャッシュ登録
end
TTSPlayer->>ExpoAudio: play(日本語音声)
ExpoAudio-->>TTSPlayer: 再生完了
TTSPlayer->>ExpoAudio: play(英語音声)
ExpoAudio-->>TTSPlayer: 再生完了
TTSPlayer-->>BGTrigger: 再生完了通知
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 分 Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@src/utils/tts/TTSPlayer.ts`:
- Around line 251-272: The code in TTSPlayer is accessing ttsJson.result and
ttsJson.result.id without validating the API response; update the fetch/parse
block to verify ttsJson and ttsJson.result exist and contain an id (and
optionally status/error fields) before creating File instances or writing audio;
if validation fails, throw or return a clear error (including the raw ttsJson)
so callers can handle it, and only call base64ToUint8Array and
fileJa.write/fileEn.write when the corresponding jaAudioContent/enAudioContent
are present; reference symbols: TTSPlayer, ttsJson, ttsJson.result.id, fileJa,
fileEn, Paths.cache, base64ToUint8Array.
🧹 Nitpick comments (5)
src/utils/tts/TTSPlayer.ts (2)
128-139: 空のcatchブロックにコメント追加を検討クリーンアップ時のエラーは無視して問題ありませんが、意図を明確にするコメントがあると保守性が向上します。
💡 提案
private cleanup(): void { try { this.soundJa?.pause(); this.soundJa?.remove(); - } catch {} + } catch { + // クリーンアップ時のエラーは無視 + } try { this.soundEn?.pause(); this.soundEn?.remove(); - } catch {} + } catch { + // クリーンアップ時のエラーは無視 + } this.soundJa = null; this.soundEn = null; }
141-226: 再生完了のタイムアウト処理を検討オーディオ再生が何らかの理由でイベントを発火しない場合、Promiseが解決されない可能性があります。タイムアウト処理の追加を検討してください。
💡 タイムアウト処理の例
private async speakFromPath(pathJa: string, pathEn: string): Promise<void> { // 既存のロジック... return new Promise((resolve) => { const TIMEOUT_MS = 60000; // 60秒 const timeoutId = setTimeout(() => { console.warn('[TTSPlayer] Playback timeout'); this.cleanup(); this.isPlaying = false; resolve(); }, TIMEOUT_MS); // イベントリスナー内でclearTimeout(timeoutId)を呼び出す // ... }); }index.js (1)
41-43: 非同期処理のエラーハンドリングを確認
triggerBackgroundTTS()は非同期関数ですが、awaitされていないため、エラーが発生した場合にキャッチされません。catchを追加するか、内部でエラーハンドリングが完結していることを確認してください。💡 修正案
setLocation(latestLocation); // Androidバックグラウンド時にTTSをトリガー - triggerBackgroundTTS(); + triggerBackgroundTTS().catch((err) => { + console.error('[Location Task] triggerBackgroundTTS error:', err); + });内部で既にtry-catchがあるため、このパターンは冗長かもしれませんが、将来的な変更に対する防御になります。
src/utils/tts/generateTTSText.ts (1)
206-366: 長いテンプレート文字列の可読性テーマ別のテンプレートは適切に構成されていますが、一部の文字列連結が非常に長くなっています。必要に応じて変数に分割することで可読性が向上する可能性があります。
src/utils/tts/helpers.ts (1)
133-146: 重複したロジック
isOedoLineとisPartiallyLoopLineは同じ条件を持っています。isOedoLineを再利用できます。💡 修正案
const isOedoLine = line ? line.id === TOEI_OEDO_LINE_ID : stations.every((s) => s.line?.id === TOEI_OEDO_LINE_ID); const isLoopLine = (() => { if (trainType && !getIsLocal(trainType)) { return false; } return isYamanoteLine || isOsakaLoopLine || isMeijoLine; })(); - const isPartiallyLoopLine = line - ? line.id === TOEI_OEDO_LINE_ID - : stations.every((s) => s.line?.id === TOEI_OEDO_LINE_ID); + const isPartiallyLoopLine = isOedoLine;
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@src/utils/tts/generateTTSText.ts`:
- Around line 85-94: Guard against findIndex returning -1 before calling slice:
check nextStationIndex and afterNextStationIndex (from the
slicedStations.findIndex calls) and if either is -1 (or afterNextStationIndex <=
nextStationIndex) set betweenNextStation to an empty array instead of slicing;
otherwise perform slicedStations.slice(nextStationIndex + 1,
afterNextStationIndex). This ensures betweenNextStation cannot become an
unintended range when findIndex fails.
- Around line 420-425: In the APP_THEME.TY case inside generateTTSText.ts (the
ARRIVING branch), guard the space+period so that when nextStationNumberText is
empty you don't emit "Name .": only prepend a space before nextStationNumberText
and conditionally append the period/terminus text when nextStationNumberText is
non-empty (or compute the trailing punctuation separately based on
isNextStopTerminus and whether nextStationNumberText exists); update the
expression around nextStation?.nameRoman + nextStationNumberText +
isNextStopTerminus to handle the empty string case, and apply the same
conditional whitespace/punctuation fix to other themes/branches that concatenate
nextStationNumberText.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@src/utils/tts/generateTTSText.test.ts`:
- Around line 6-35: Add an afterEach hook to the generateTTSText test file that
calls jest.clearAllMocks() so mocks are reset between tests; place it in the
same scope as createBaseData within the describe('generateTTSText', ...) block
(i.e., add afterEach(() => jest.clearAllMocks());) to ensure all mocks/spies are
cleared after each test.
In `@src/utils/tts/generateTTSText.ts`:
- Around line 130-132: The current single-station branch in generateTTSText
produces e.g. "02" (or "Station Number 02") without a trailing period which
breaks Tokyo Metro English phrasing; update getStationNumberText to always
return the station-number string with a trailing period (e.g., "02." or "Station
Number 02.") for the single-number case and have generateTTSText call
getStationNumberText (using nextStationNumber.stationNumber and honoring
APP_THEME.JR_WEST) instead of inline formatting so the period is consistently
present; adjust logic that uses split to rely on getStationNumberText’s output.
#5133
Summary by CodeRabbit
新機能
改善
削除
テスト
✏️ Tip: You can customize this high-level summary in your review settings.