-
Notifications
You must be signed in to change notification settings - Fork 6
feat(reminder): add audio playback and interval time adapters #267
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Wintercom
merged 7 commits into
1024XEngineer:main
from
LUPENGHAN:feature/reminder-adapters-audio
Aug 19, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8892a3e
feat(reminder): add audio playback and interval time adapters
LUPENGHAN d973f40
fix(reminder): retry audio mode setup after a failed attempt
LUPENGHAN 3c3b250
fix(reminder): wire IntervalTimeListener into the composition root
LUPENGHAN e718dcf
test(reminder): cover the audio and interval-time adapters
LUPENGHAN e6275ea
style(reminder): run prettier on ExpoAudioPlayback and its test
LUPENGHAN 237a169
fix(reminder): report played: false when audio mode setup fails
LUPENGHAN b385082
fix(reminder): wire LocalReminderApplication into the composition root
LUPENGHAN File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| import type { | ||
| AudioPlaybackPort, | ||
| AudioPlaybackReceipt, | ||
| AudioPlaybackRequest, | ||
| } from '../../features/reminder/application/interfaces'; | ||
| import { buildAudioDataUri } from './audioDataUri'; | ||
|
|
||
| // Metro 资源 id;高强度本地兜底铃声(与原生 AlarmSoundService 同源)。 | ||
| const LOCAL_ALARM_SOUND = require('../../../assets/sounds/alarm_prompt.mp3') as number; | ||
|
|
||
| type AudioPlayerLike = { | ||
| pause: () => void; | ||
| replace: (source: string | number) => void; | ||
| play: () => void; | ||
| volume: number; | ||
| loop: boolean; | ||
| }; | ||
|
|
||
| type ExpoAudioModule = { | ||
| createAudioPlayer: (source?: string | number | null) => AudioPlayerLike; | ||
| setAudioModeAsync: (mode: Record<string, unknown>) => Promise<void>; | ||
| }; | ||
|
|
||
| /** | ||
| * 音频播放适配器: | ||
| * - TTS 有字节时播放并循环,直到 stop | ||
| * - 否则播放打包的 alarm_prompt.mp3(高强度本地兜底) | ||
| */ | ||
| export class ExpoAudioPlayback implements AudioPlaybackPort { | ||
| private player: AudioPlayerLike | null = null; | ||
| private activeScheduleId: string | null = null; | ||
| private modeReady: Promise<void> | null = null; | ||
|
|
||
| /** 默认走真实的动态 import;测试注入一个假实现,绕开 expo-audio 这个原生模块。 */ | ||
| constructor( | ||
| private readonly loadExpoAudioModule: () => Promise<ExpoAudioModule | null> = loadExpoAudio, | ||
| ) {} | ||
|
|
||
| async isTtsAvailable(): Promise<boolean> { | ||
| // TTS 字节管线尚未接入;有 data 时由 playTts 直接播放。 | ||
| return false; | ||
| } | ||
|
|
||
| async playTts(request: AudioPlaybackRequest): Promise<AudioPlaybackReceipt> { | ||
| if (request.data == null || request.data.byteLength === 0) { | ||
| return { | ||
| playback_id: `tts-empty-${request.schedule_id}`, | ||
| played: false, | ||
| used_local_fallback: false, | ||
| }; | ||
| } | ||
| const played = await this.playBytes(request.schedule_id, request.data, request.format ?? 'wav'); | ||
| return { | ||
| playback_id: `tts-${request.schedule_id}`, | ||
| played, | ||
| used_local_fallback: false, | ||
| }; | ||
| } | ||
|
|
||
| async playLocalFallback(request: AudioPlaybackRequest): Promise<AudioPlaybackReceipt> { | ||
| if (request.data != null && request.data.byteLength > 0) { | ||
| const played = await this.playBytes( | ||
| request.schedule_id, | ||
| request.data, | ||
| request.format ?? 'wav', | ||
| ); | ||
| return { | ||
| playback_id: `local-${request.schedule_id}`, | ||
| played, | ||
| used_local_fallback: true, | ||
| }; | ||
| } | ||
|
|
||
| const played = await this.playBundledAlarm(request.schedule_id); | ||
| return { | ||
| playback_id: `local-bundled-${request.schedule_id}`, | ||
| played, | ||
| used_local_fallback: true, | ||
| }; | ||
| } | ||
|
|
||
| async stop(scheduleId: string): Promise<void> { | ||
| if (this.activeScheduleId !== scheduleId) return; | ||
| if (this.player != null) { | ||
| this.player.loop = false; | ||
| this.player.pause(); | ||
| } | ||
| this.activeScheduleId = null; | ||
| } | ||
|
|
||
| private async playBytes(scheduleId: string, data: Uint8Array, format: string): Promise<boolean> { | ||
| const expoAudio = await this.loadExpoAudioModule(); | ||
| if (expoAudio == null) return false; | ||
| if (!(await this.ensureAudioMode(expoAudio))) return false; | ||
|
|
||
| const player = this.ensurePlayer(expoAudio); | ||
| player.pause(); | ||
| player.replace(buildAudioDataUri(data, format)); | ||
| player.loop = true; | ||
| player.volume = 1; | ||
| this.activeScheduleId = scheduleId; | ||
| player.play(); | ||
| return true; | ||
| } | ||
|
|
||
| private async playBundledAlarm(scheduleId: string): Promise<boolean> { | ||
| const expoAudio = await this.loadExpoAudioModule(); | ||
| if (expoAudio == null) return false; | ||
| if (!(await this.ensureAudioMode(expoAudio))) return false; | ||
|
|
||
| const player = this.ensurePlayer(expoAudio); | ||
| player.pause(); | ||
| player.replace(LOCAL_ALARM_SOUND); | ||
| player.loop = true; | ||
| player.volume = 1; | ||
| this.activeScheduleId = scheduleId; | ||
| player.play(); | ||
| return true; | ||
| } | ||
|
|
||
| private ensurePlayer(expoAudio: ExpoAudioModule): AudioPlayerLike { | ||
| if (this.player == null) { | ||
| this.player = expoAudio.createAudioPlayer(null); | ||
| } | ||
| return this.player; | ||
| } | ||
|
|
||
| /** | ||
| * 返回 false 时调用方必须放弃这次播放,不能假装播放成功——静音模式/后台播放 | ||
| * 没配置成功,即使真的调用 play() 用户也大概率听不到。不永久缓存失败:清掉 | ||
| * modeReady 让下一次响铃重新尝试,而不是这次失败后整个 App 生命周期都跳过。 | ||
| */ | ||
| private async ensureAudioMode(expoAudio: ExpoAudioModule): Promise<boolean> { | ||
| if (this.modeReady == null) { | ||
| this.modeReady = expoAudio.setAudioModeAsync({ | ||
| allowsRecording: false, | ||
| interruptionMode: 'doNotMix', | ||
| playsInSilentMode: true, | ||
| shouldPlayInBackground: true, | ||
| shouldRouteThroughEarpiece: false, | ||
| }); | ||
| } | ||
| try { | ||
| await this.modeReady; | ||
| return true; | ||
| } catch { | ||
| this.modeReady = null; | ||
| return false; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| async function loadExpoAudio(): Promise<ExpoAudioModule | null> { | ||
| try { | ||
| const mod = await import('expo-audio'); | ||
| if (typeof mod.createAudioPlayer !== 'function') return null; | ||
| return mod as unknown as ExpoAudioModule; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; | ||
|
|
||
| const MIME_BY_FORMAT: Record<string, string> = { | ||
| aac: 'audio/aac', | ||
| m4a: 'audio/mp4', | ||
| mp3: 'audio/mpeg', | ||
| mpeg: 'audio/mpeg', | ||
| oga: 'audio/ogg', | ||
| ogg: 'audio/ogg', | ||
| wav: 'audio/wav', | ||
| wave: 'audio/wav', | ||
| }; | ||
|
|
||
| export function encodeBase64(bytes: Uint8Array): string { | ||
| let output = ''; | ||
| for (let index = 0; index < bytes.length; index += 3) { | ||
| const first = bytes[index] ?? 0; | ||
| const hasSecond = index + 1 < bytes.length; | ||
| const hasThird = index + 2 < bytes.length; | ||
| const second = hasSecond ? bytes[index + 1]! : 0; | ||
| const third = hasThird ? bytes[index + 2]! : 0; | ||
| const value = (first << 16) | (second << 8) | third; | ||
|
|
||
| output += BASE64_ALPHABET[(value >>> 18) & 63]; | ||
| output += BASE64_ALPHABET[(value >>> 12) & 63]; | ||
| output += hasSecond ? BASE64_ALPHABET[(value >>> 6) & 63] : '='; | ||
| output += hasThird ? BASE64_ALPHABET[value & 63] : '='; | ||
| } | ||
| return output; | ||
| } | ||
|
|
||
| export function buildAudioDataUri(bytes: Uint8Array, audioFormat: string): string { | ||
| const normalizedFormat = audioFormat.trim().toLowerCase().replace(/^\./, ''); | ||
| if (!/^[a-z0-9][a-z0-9.+-]{0,31}$/.test(normalizedFormat)) { | ||
| throw new Error('Unsupported reminder audio format'); | ||
| } | ||
| const mime = MIME_BY_FORMAT[normalizedFormat] ?? `audio/${normalizedFormat}`; | ||
| return `data:${mime};base64,${encodeBase64(bytes)}`; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| export { MockAudioPlayback } from './MockAudioPlayback'; | ||
| export { ExpoAudioPlayback } from './ExpoAudioPlayback'; | ||
| export { buildAudioDataUri, encodeBase64 } from './audioDataUri'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import type { | ||
| LocalTimeTick, | ||
| TimeListenerHandle, | ||
| TimeListenerOptions, | ||
| TimeListenerPort, | ||
| } from '../../features/reminder/application/interfaces'; | ||
|
|
||
| const DEFAULT_INTERVAL_MS = 30_000; | ||
|
|
||
| /** 进程内周期时间观测,驱动 handleTime。 */ | ||
| export class IntervalTimeListener implements TimeListenerPort { | ||
| private readonly timers = new Map<string, ReturnType<typeof setInterval>>(); | ||
| private sequence = 0; | ||
|
|
||
| constructor(private readonly intervalMs: number = DEFAULT_INTERVAL_MS) {} | ||
|
|
||
| async start( | ||
| listener: (tick: LocalTimeTick) => void, | ||
| _options?: TimeListenerOptions, | ||
| ): Promise<TimeListenerHandle> { | ||
| const listenerId = `interval-time-listener-${++this.sequence}`; | ||
| const emit = () => { | ||
| listener({ observed_at: new Date().toISOString() }); | ||
| }; | ||
| // 不在 start 同步打首 tick,交给调用方完成 rebuild 后再自然周期触发。 | ||
| const timer = setInterval(emit, this.intervalMs); | ||
| this.timers.set(listenerId, timer); | ||
| return { listener_id: listenerId }; | ||
| } | ||
|
|
||
| async stop(listenerId: string): Promise<void> { | ||
| const timer = this.timers.get(listenerId); | ||
| if (timer != null) { | ||
| clearInterval(timer); | ||
| this.timers.delete(listenerId); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| export { MockTimeListener } from './MockTimeListener'; | ||
| export { IntervalTimeListener } from './IntervalTimeListener'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| declare module 'expo-audio' { | ||
| export function createAudioPlayer(source?: string | number | null): { | ||
| pause: () => void; | ||
| replace: (source: string | number) => void; | ||
| play: () => void; | ||
| volume: number; | ||
| loop: boolean; | ||
| }; | ||
|
|
||
| export function setAudioModeAsync(mode: Record<string, unknown>): Promise<void>; | ||
| } | ||
|
|
||
| declare module '*.mp3' { | ||
| const asset: number; | ||
| export default asset; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.