WIP: global player refactor pt. 1
This commit is contained in:
46
src/lib/components/player/ctx.svelte.ts
Normal file
46
src/lib/components/player/ctx.svelte.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user