Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/Trale/miniapp-src/src/alphabet/games/fx.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { playClip, registerAudioContext } from './fx'

// iPhone держит плеер «TraleBot» на экране блокировки, пока у страницы есть <audio> с файлом.
describe('звук не числится играющим после записи и в свёрнутом мини-аппе', () => {
const made: HTMLAudioElement[] = []
beforeEach(() => {
made.length = 0
vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(function (this: HTMLMediaElement) {
made.push(this as HTMLAudioElement)
return Promise.resolve()
})
vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {})
})

const hide = () => {
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
document.dispatchEvent(new Event('visibilitychange'))
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })
}

it('lets go of the file once the clip has played, and takes it again for the next play', async () => {
await playClip('/audio/a.m4a')
const el = made[made.length - 1]!
expect(el.getAttribute('src')).toBe('/audio/a.m4a')
el.dispatchEvent(new Event('ended'))
expect(el.getAttribute('src')).toBeNull()

await playClip('/audio/a.m4a')
expect(made[made.length - 1]).toBe(el)
expect(el.getAttribute('src')).toBe('/audio/a.m4a')
})

it('silences clips, sound contexts and the now-playing card when the mini-app is hidden', async () => {
await playClip('/audio/b.m4a')
const el = made[made.length - 1]!
const ctx = { state: 'running', suspend: vi.fn(async () => {}) } as unknown as AudioContext
registerAudioContext(ctx)
const mediaSession = { metadata: {}, playbackState: 'playing' }
Object.defineProperty(navigator, 'mediaSession', { value: mediaSession, configurable: true })

hide()

expect(el.getAttribute('src')).toBeNull()
expect(ctx.suspend).toHaveBeenCalled()
expect(mediaSession).toEqual({ metadata: null, playbackState: 'none' })
})
})
39 changes: 38 additions & 1 deletion src/Trale/miniapp-src/src/alphabet/games/fx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function context(): AudioContext | null {
if (!Ctor) return null
playbackSession()
ctx = new Ctor()
registerAudioContext(ctx!)
return ctx
} catch { return null }
}
Expand Down Expand Up @@ -97,7 +98,13 @@ let unlocked = false
export async function unlockAudio(): Promise<void> {
if (unlocked) return
playbackSession()
const tag = (() => { try { const el = new Audio(SILENT_WAV); el.setAttribute('playsinline', ''); return safePlay(el).catch(() => {}) } catch { return Promise.resolve() } })()
const tag = (() => {
try {
const el = new Audio(SILENT_WAV)
el.setAttribute('playsinline', '')
return safePlay(el).catch(() => {}).finally(() => releaseAudio(el))
} catch { return Promise.resolve() }
})()
const a = context()
if (a) {
try {
Expand Down Expand Up @@ -135,6 +142,19 @@ function withAudio(play: (a: AudioContext) => void) {

// ───────────── Записи (буквы) ─────────────

// iPhone держит плеер «TraleBot» на экране блокировки, пока у страницы есть <audio> с записью, —
// даже доигравшей. Поэтому доигравшая запись отпускает файл (следующий раз он берётся из кеша),
// а свёрнутый мини-апп глушит всё: записи, контексты WebAudio и карточку «Сейчас играет».

/** Отпустить файл записи — для iOS это конец воспроизведения, плеер с экрана блокировки уходит. */
export function releaseAudio(el: HTMLAudioElement) {
try { el.pause(); el.removeAttribute('src'); el.load() } catch { /* уже отпущена */ }
}

const contexts = new Set<AudioContext>()
/** Контекст WebAudio, который надо усыплять, когда мини-апп свёрнут; будится первым касанием. */
export function registerAudioContext(a: AudioContext) { contexts.add(a) }

const clips = new Map<string, HTMLAudioElement>()
function clip(url: string): HTMLAudioElement | null {
try {
Expand All @@ -143,12 +163,29 @@ function clip(url: string): HTMLAudioElement | null {
el = new Audio(url)
el.preload = 'auto'
el.setAttribute('playsinline', '')
el.addEventListener('ended', () => releaseAudio(el!))
clips.set(url, el)
}
if (!el.getAttribute('src')) el.src = url
return el
} catch { return null }
}

/** Мини-апп свёрнут: ничего не играет и не числится играющим. */
export function silenceForBackground() {
for (const el of clips.values()) releaseAudio(el)
for (const a of contexts) { try { if (a.state === 'running') void a.suspend().catch(() => {}) } catch { /* закрыт */ } }
try {
const ms = (navigator as any).mediaSession
if (ms) { ms.metadata = null; ms.playbackState = 'none' }
} catch { /* нет API */ }
}

if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') silenceForBackground() })
window.addEventListener('pagehide', silenceForBackground)
}

/** Сыграть запись (уважает выключатель звука). */
export function playClip(url: string): Promise<void> {
if (muted) return Promise.resolve()
Expand Down
7 changes: 6 additions & 1 deletion src/Trale/miniapp-src/src/components/AudioPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export default function AudioPlayer({ url, onPlayed, onError }: AudioPlayerProps
audioRef.current = audio

const onEnded = () => {
// Отпустить файл: иначе iPhone держит плеер на экране блокировки и после выхода из мини-аппа.
audio.removeAttribute('src')
audio.load()
setState('played')
if (!playedOnceRef.current) {
playedOnceRef.current = true
Expand Down Expand Up @@ -51,14 +54,16 @@ export default function AudioPlayer({ url, onPlayed, onError }: AudioPlayerProps

if (state === 'idle' || state === 'played') {
setState('loading')
if (!audio.getAttribute('src')) audio.src = url
audio.currentTime = 0
audio
.play()
.then(() => setState('playing'))
.catch(() => setState('error'))
} else if (state === 'playing') {
audio.pause()
audio.currentTime = 0
audio.removeAttribute('src')
audio.load()
setState('idle')
}
// loading and error: no-op on tap
Expand Down
4 changes: 2 additions & 2 deletions src/Trale/miniapp-src/src/myday/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
// подсказками по одной у нужного элемента.
// Всё перетаскивается пальцем, тап — тоже ход. Записи — public/audio/myday/<id>.m4a (ElevenLabs «Alice»,
// eleven_v4, ka). Вибрация и выключатель звука — общие с играми алфавита (alphabet/games/fx).
import { haptic, isMuted, playClip } from '../alphabet/games/fx'
import { haptic, isMuted, playClip, registerAudioContext } from '../alphabet/games/fx'
import { ICON, EAR, BACK } from './icons'
import { bomboraBody, bomboraHead, bomboraRig, catBody } from './puppets'

Expand Down Expand Up @@ -36,7 +36,7 @@ async function decode(id) {
async function unlock() {
if (ac) { if (ac.state === 'suspended') ac.resume().catch(() => {}); return }
const C = window.AudioContext || window.webkitAudioContext; if (!C) return
ac = new C(); try { await ac.resume() } catch {}
ac = new C(); registerAudioContext(ac); try { await ac.resume() } catch {}
Object.keys(raw).forEach(decode)
}
function say(id) {
Expand Down
4 changes: 2 additions & 2 deletions src/Trale/miniapp-src/src/numbers/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// Модуль «Числа»: десять уровней. Перед игрой — интерактивный объяснятор (как устроены числа этого промежутка),
// внутри уровня подсказки постепенно исчезают. Записи чисел 1–99 — public/audio/numbers/n/<число>.m4a
// (ElevenLabs «Alice», eleven_v4, ka). Вибрация и выключатель звука — общие с играми алфавита (alphabet/games/fx).
import { haptic, isMuted, playClip } from '../alphabet/games/fx'
import { haptic, isMuted, playClip, registerAudioContext } from '../alphabet/games/fx'

// ───────── Общее: транскрипция, звук, вибрация ─────────
const CYR = { 'ა':'а','ბ':'б','გ':'г','დ':'д','ე':'э','ვ':'в','ზ':'з','თ':'т','ი':'и','კ':'к’','ლ':'л','მ':'м','ნ':'н','ო':'о','პ':'п’','ჟ':'ж','რ':'р','ს':'с','ტ':'т’','უ':'у','ფ':'п','ქ':'к','ღ':'гх','ყ':'къ','შ':'ш','ჩ':'ч','ც':'ц','ძ':'дз','წ':'ц’','ჭ':'ч’','ხ':'х','ჯ':'дж','ჰ':'х' };
Expand Down Expand Up @@ -31,7 +31,7 @@ async function decode(n) {
async function unlock() {
if (ac) { if (ac.state === 'suspended') ac.resume().catch(() => {}); return; }
const C = window.AudioContext || window.webkitAudioContext; if (!C) return;
ac = new C(); try { await ac.resume(); } catch {}
ac = new C(); registerAudioContext(ac); try { await ac.resume(); } catch {}
Object.keys(raw).forEach(n => decode(+n));
}
function say(n) {
Expand Down
Loading