Files
stemengine_old/frontend/src/utils/audioRegistry.ts
T
2026-03-03 14:52:19 +09:00

102 lines
3.1 KiB
TypeScript
Executable File

/**
* Global audio playback registry.
*
* Only one audio player should be playing at a time. When a player starts,
* it registers a stop callback here. Any previously registered callback is
* called first, pausing the old player before the new one starts.
*
* Players also publish live state so the GlobalAudioBar can reflect playback
* position, title and play/pause status across page navigation.
*/
type StopFn = () => void
export interface PlaybackMeta {
title: string
isPlaying: boolean
currentTime: number
duration: number
volume: number
}
export interface PlaybackActions {
toggle: () => void
seek: (t: number) => void
setVolume: (v: number) => void
}
let _current: StopFn | null = null
// Mutable singleton — players overwrite toggle/seek/setVolume in-place each render,
// so the bar always invokes the freshest closures without any ref gymnastics.
const _actions: PlaybackActions = { toggle: () => {}, seek: () => {}, setVolume: () => {} }
let _meta: PlaybackMeta | null = null
const _listeners = new Set<() => void>()
// ── Stop / unregister ────────────────────────────────────────────────────────
/**
* Call this when a player begins playback.
* The previously active player (if any) will be stopped.
*/
export function registerPlayback(stop: StopFn): void {
if (_current && _current !== stop) {
_current()
}
_current = stop
}
/**
* Call this when a player unmounts or hard-resets so the registry no
* longer holds a stale reference. Do NOT call on simple pause — let the
* registry keep holding the player so the bar stays visible.
*/
export function unregisterPlayback(stop: StopFn): void {
if (_current === stop) {
_current = null
}
}
// ── Bar state ────────────────────────────────────────────────────────────────
/**
* Players call this whenever their state changes (play, pause, seek, RAF tick).
* The mutable _actions singleton is updated in-place so the bar always has
* fresh callbacks without needing extra refs.
*/
export function publishMeta(meta: PlaybackMeta, actions: PlaybackActions): void {
_meta = meta
_actions.toggle = actions.toggle
_actions.seek = actions.seek
_actions.setVolume = actions.setVolume
_listeners.forEach(l => l())
}
/**
* Call this when the player is forcibly stopped (registry takeover) or unmounts.
* Simple pause should NOT clear — the bar stays visible showing paused state.
*/
export function clearMeta(): void {
if (_meta !== null) {
_meta = null
_listeners.forEach(l => l())
}
}
export function getMeta(): PlaybackMeta | null {
return _meta
}
export function getActions(): PlaybackActions {
return _actions
}
/**
* Subscribe to bar state changes. Returns an unsubscribe function.
*/
export function subscribePlayback(listener: () => void): () => void {
_listeners.add(listener)
return () => _listeners.delete(listener)
}