creative-brain-os / frontend /src /lib /samplePlayer.ts
kpranav022's picture
Claude Fable 5.1
Cast real people with their own voices, sell the product you attached, and take five-minute ads
7dfe8d4
Raw History Blame Contribute Delete
1.7 kB
/** One voice-sample player for the whole app, so starting a sample anywhere —
* the grid, the picker, a chip — stops whichever one was playing. */
import { useSyncExternalStore } from "react";
export type SampleState = { id: string | null; playing: boolean; current: number; duration: number };
let state: SampleState = { id: null, playing: false, current: 0, duration: 0 };
let audio: HTMLAudioElement | null = null;
const listeners = new Set<() => void>();
function emit(next: Partial<SampleState>) {
state = { ...state, ...next };
listeners.forEach((l) => l());
}
function el(): HTMLAudioElement {
if (audio) return audio;
audio = new Audio();
audio.preload = "metadata";
audio.addEventListener("timeupdate", () => emit({ current: audio!.currentTime }));
audio.addEventListener("loadedmetadata", () => emit({ duration: audio!.duration || 0 }));
audio.addEventListener("play", () => emit({ playing: true }));
audio.addEventListener("pause", () => emit({ playing: false }));
audio.addEventListener("ended", () => emit({ playing: false, current: 0 }));
return audio;
}
export function toggleSample(id: string, url: string): void {
const a = el();
if (state.id === id) {
if (a.paused) void a.play().catch(() => emit({ playing: false }));
else a.pause();
return;
}
a.pause();
a.src = url;
emit({ id, playing: false, current: 0, duration: 0 });
void a.play().catch(() => emit({ playing: false }));
}
export function stopSample(): void {
audio?.pause();
}
export function useSample(): SampleState {
return useSyncExternalStore(
(l) => {
listeners.add(l);
return () => listeners.delete(l);
},
() => state,
);
}