Files
amqtrain/src/lib/components/player/ctx.svelte.ts

47 lines
815 B
TypeScript

import { getContext, setContext } from "svelte";
const AUDIO_CTX_KEY = "amqtrain:player:audio-ctx";
export class AudioContext {
currentTime = $state(0);
duration = $state(0);
paused = $state(true);
private audioEl: HTMLAudioElement | null = null;
constructor() {}
setElement(el: HTMLAudioElement) {
this.audioEl = el;
}
play() {
this.audioEl?.play();
}
pause() {
this.audioEl?.pause();
}
toggle() {
if (this.paused) this.play();
else this.pause();
}
seek(time: number) {
if (this.audioEl) {
this.audioEl.currentTime = Math.max(0, Math.min(time, this.duration));
}
}
}
export function setAudioContext() {
const ctx = new AudioContext();
setContext(AUDIO_CTX_KEY, ctx);
return ctx;
}
export function getAudioContext() {
return getContext<AudioContext>(AUDIO_CTX_KEY);
}