Audio Store (#3)
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'svelte-podcast': minor
|
||||
---
|
||||
|
||||
Adds initial audio element abstraction with store
|
||||
+6
-6
@@ -28,20 +28,22 @@
|
||||
"svelte": "^3.54.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.26.0",
|
||||
"@playwright/test": "^1.28.1",
|
||||
"@sveltejs/adapter-auto": "^2.0.0",
|
||||
"@sveltejs/kit": "^1.5.0",
|
||||
"@sveltejs/package": "^2.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.45.0",
|
||||
"@typescript-eslint/parser": "^5.45.0",
|
||||
"eslint": "^8.28.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-plugin-svelte3": "^4.0.0",
|
||||
"prettier": "^2.8.0",
|
||||
"eslint": "^8.28.0",
|
||||
"just-clamp": "^4.2.0",
|
||||
"prettier-plugin-svelte": "^2.8.1",
|
||||
"prettier": "^2.8.0",
|
||||
"publint": "^0.1.9",
|
||||
"svelte": "^3.54.0",
|
||||
"svelte-check": "^3.0.1",
|
||||
"svelte": "^3.54.0",
|
||||
"tslib": "^2.4.1",
|
||||
"typescript": "^4.9.3",
|
||||
"vite": "^4.0.0"
|
||||
@@ -49,7 +51,5 @@
|
||||
"svelte": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@changesets/cli": "^2.26.0"
|
||||
}
|
||||
"dependencies": {}
|
||||
}
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
<script lang="ts">
|
||||
import AudioA11yProgress from '$lib/components/audio-a11y-progress.svelte';
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import { usePlayer, type PlayerElement } from './audio';
|
||||
|
||||
// TODO: Abstract to a store so we can add actions like reqind 20s
|
||||
|
||||
export let src: string;
|
||||
export let autoplay: boolean;
|
||||
|
||||
export let currentTime = 0;
|
||||
export let muted = false;
|
||||
export let paused = true;
|
||||
export let playbackRate = 1;
|
||||
export let volume = 0;
|
||||
|
||||
let audioElement: PlayerElement;
|
||||
|
||||
$: usePlayer(audioElement, 'playbackRate', playbackRate);
|
||||
|
||||
const dispatch = createEventDispatcher<{
|
||||
playing: void;
|
||||
finished: void;
|
||||
paused: { currentTime: number };
|
||||
progress: { currentTime: number };
|
||||
seek: { currentTime: number };
|
||||
rateChange: { playbackRate: number };
|
||||
}>();
|
||||
|
||||
let duration = 0;
|
||||
</script>
|
||||
|
||||
{#key src}
|
||||
<audio
|
||||
bind:this={audioElement}
|
||||
{src}
|
||||
{autoplay}
|
||||
bind:currentTime
|
||||
bind:duration
|
||||
bind:paused
|
||||
bind:muted
|
||||
bind:volume
|
||||
preload="metadata"
|
||||
controls={false}
|
||||
on:timeupdate={() => dispatch('progress', { currentTime })}
|
||||
on:playing={() => dispatch('playing')}
|
||||
on:pause={() => dispatch('paused', { currentTime })}
|
||||
on:ratechange={() => dispatch('rateChange', { playbackRate })}
|
||||
on:ended={() => dispatch('finished')}
|
||||
on:seeked={() => dispatch('seek', { currentTime })}
|
||||
on:durationchange={() => console.log('durationchange')}
|
||||
on:loadeddata={() => console.log('loaded data')}
|
||||
on:loadedmetadata={() => console.log('loadedmetadata')}
|
||||
on:loadstart={() => console.log('load start')}
|
||||
on:seeking={() => console.log('seeking')}
|
||||
on:suspend={() => console.log('suspend')}
|
||||
on:volumechange={() => console.log('volumechange')}
|
||||
on:play={() => console.log('play')}
|
||||
on:canplay={() => console.log('canplay')}
|
||||
on:canplaythrough={() => console.log('canplaythrough')}
|
||||
on:waiting={() => console.log('waiting')}
|
||||
on:stalled={(e) => console.log('stalled', e)}
|
||||
on:emptied={(e) => console.log('emptied', e)}
|
||||
on:load={(e) => console.log('load', e)}
|
||||
/>
|
||||
<AudioA11yProgress {currentTime} {paused} {duration} />
|
||||
<slot {duration} />
|
||||
{/key}
|
||||
@@ -1,10 +0,0 @@
|
||||
export type PlayerElement = HTMLAudioElement | undefined;
|
||||
|
||||
export function usePlayer<K extends keyof HTMLAudioElement>(
|
||||
el: PlayerElement,
|
||||
key: K,
|
||||
value: HTMLAudioElement[K],
|
||||
) {
|
||||
if (!el) return;
|
||||
el[key] = value;
|
||||
}
|
||||
+2
-7
@@ -4,15 +4,10 @@
|
||||
export let duration: number;
|
||||
</script>
|
||||
|
||||
<progress
|
||||
class="svelte-podcast-a11y-hidden"
|
||||
data-paused={paused ? 'true' : 'false'}
|
||||
max={duration}
|
||||
value={currentTime}
|
||||
/>
|
||||
<progress data-paused={paused ? 'true' : 'false'} max={duration} value={currentTime} />
|
||||
|
||||
<style>
|
||||
.svelte-podcast-a11y-hidden {
|
||||
progress {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
@@ -0,0 +1,76 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
__internal_audio_current_time,
|
||||
__internal_audio_element,
|
||||
__internal_audio_metadata,
|
||||
__internal_audio_src,
|
||||
} from '$lib/components/audio/store';
|
||||
import type { PlayerElement } from '$lib/components/audio/types';
|
||||
import { isBoolean, isNumber } from '$lib/helper/check';
|
||||
|
||||
let element: PlayerElement;
|
||||
let currentTime = 0;
|
||||
let muted = false;
|
||||
|
||||
$: src = $__internal_audio_src;
|
||||
$: __internal_audio_element.set(element);
|
||||
$: __internal_audio_current_time.set(currentTime);
|
||||
$: __internal_audio_metadata.update((x) => ({ ...x, muted }));
|
||||
</script>
|
||||
|
||||
{#key src}
|
||||
<audio
|
||||
bind:this={element}
|
||||
{src}
|
||||
autoplay={false}
|
||||
bind:currentTime
|
||||
bind:muted
|
||||
preload="metadata"
|
||||
controls={false}
|
||||
on:canplay={(e) => false && console.log('canplay', e)}
|
||||
on:canplaythrough={(e) => false && console.log('canplaythrough', e)}
|
||||
on:timeupdate={(e) => false && console.log('progress', e)}
|
||||
on:loadedmetadata={(e) => false && console.log('loadedmetadata', e)}
|
||||
on:suspend={(e) => false && console.log('suspend', e)}
|
||||
on:seeked={(e) => false && console.log('seeked', e)}
|
||||
on:play={(e) => false && console.log('play', e)}
|
||||
on:waiting={(e) => console.log('waiting', e)}
|
||||
on:stalled={(e) => console.log('stalled', e)}
|
||||
on:load={(e) => console.log('load', e)}
|
||||
on:emptied={() => {
|
||||
// TODO: reset player state
|
||||
// console.log('emptied', e);
|
||||
}}
|
||||
on:loadeddata={() => {
|
||||
__internal_audio_metadata.update((m) => ({ ...m, loading: false }));
|
||||
}}
|
||||
on:loadstart={() => {
|
||||
__internal_audio_metadata.update((m) => ({ ...m, loading: true }));
|
||||
}}
|
||||
on:playing={(e) => {
|
||||
// @ts-expect-error event is not fully typed
|
||||
const is_paused = e.target.paused;
|
||||
if (!isBoolean(is_paused)) return;
|
||||
__internal_audio_metadata.update((m) => ({ ...m, paused: is_paused }));
|
||||
}}
|
||||
on:pause={(e) => {
|
||||
// @ts-expect-error event is not fully typed
|
||||
const is_paused = e.target.paused;
|
||||
if (!isBoolean(is_paused)) return;
|
||||
__internal_audio_metadata.update((m) => ({ ...m, paused: is_paused }));
|
||||
}}
|
||||
on:ratechange={(e) => {
|
||||
// @ts-expect-error event is not fully typed
|
||||
const playbackRate = e.target.playbackRate;
|
||||
if (!isNumber(playbackRate)) return;
|
||||
__internal_audio_metadata.update((m) => ({ ...m, playbackRate }));
|
||||
}}
|
||||
on:durationchange={(e) => {
|
||||
// @ts-expect-error event is not fully typed
|
||||
const duration = e.target?.duration;
|
||||
if (!isNumber(duration)) return;
|
||||
__internal_audio_metadata.update((m) => ({ ...m, duration }));
|
||||
}}
|
||||
/>
|
||||
<!-- <AudioA11yProgress {currentTime} {paused} {duration} /> -->
|
||||
{/key}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as AudioManager } from './audio.svelte';
|
||||
export { audio } from './store';
|
||||
@@ -0,0 +1,143 @@
|
||||
import { dev } from '$app/environment';
|
||||
import type { PlayerElement, PlayerMetadata } from '$lib/components/audio/types';
|
||||
import { secondsToTimestamp } from '$lib/helper/seconds-to-timestamp';
|
||||
import clamp from 'just-clamp';
|
||||
import { derived, writable } from 'svelte/store';
|
||||
|
||||
function log(...val: (string | number | boolean)[]) {
|
||||
if (!dev) return;
|
||||
console.info('🎶 ', ...val);
|
||||
}
|
||||
function warn(...val: (string | number | boolean)[]) {
|
||||
if (!dev) return;
|
||||
console.warn('🎶 ', ...val);
|
||||
}
|
||||
|
||||
export const __internal_audio_current_time = writable<number>(0);
|
||||
export const __internal_audio_src = writable<string | null>(null);
|
||||
export const __internal_audio_element = writable<PlayerElement>();
|
||||
export const __internal_audio_metadata = writable<PlayerMetadata>({
|
||||
duration: 0,
|
||||
muted: false,
|
||||
paused: true,
|
||||
playbackRate: 1,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
const state = derived(
|
||||
[__internal_audio_metadata, __internal_audio_current_time],
|
||||
([$metadata, $current_time]) => {
|
||||
return {
|
||||
current_time: $current_time,
|
||||
timestamp: secondsToTimestamp($current_time),
|
||||
...$metadata,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
type HandleType = 'toggle' | 'set';
|
||||
|
||||
function play(type: HandleType = 'set') {
|
||||
log('play: ', type);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
if (type === 'toggle') {
|
||||
el.paused ? el.play() : el.pause();
|
||||
} else {
|
||||
el.play();
|
||||
}
|
||||
})();
|
||||
}
|
||||
function pause(type: HandleType = 'set') {
|
||||
log('pause: ', type);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
if (type === 'toggle') {
|
||||
el.paused ? el.play() : el.pause();
|
||||
} else {
|
||||
el.pause();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
function mute(type: HandleType = 'set') {
|
||||
log('mute: ', type);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
if (type === 'toggle') {
|
||||
el.muted = !el.muted;
|
||||
} else {
|
||||
el.muted = true;
|
||||
}
|
||||
})();
|
||||
}
|
||||
function unmute(type: HandleType = 'set') {
|
||||
log('unmute: ', type);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
if (type === 'toggle') {
|
||||
el.muted = !el.muted;
|
||||
} else {
|
||||
el.muted = false;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
function load(src: string) {
|
||||
log('load: ', src);
|
||||
__internal_audio_src.set(src);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
el.volume = 1;
|
||||
el.pause();
|
||||
})();
|
||||
}
|
||||
function unload() {
|
||||
log('unload: ');
|
||||
__internal_audio_src.set(null);
|
||||
}
|
||||
|
||||
function setPlaybackRate(rate: number) {
|
||||
log('setPlaybackRate: ', rate);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
el.playbackRate = clamp(0, 10, rate);
|
||||
})();
|
||||
}
|
||||
|
||||
function seek(seconds: number, from: 'from-start' | 'from-end' = 'from-start') {
|
||||
log('seek: ', seconds, from);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
if (from === 'from-end') {
|
||||
el.currentTime = clamp(0, el.duration, el.duration - seconds);
|
||||
} else {
|
||||
el.currentTime = clamp(0, el.duration, seconds);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
function skip(seconds: number, type: 'forward' | 'backward' = 'forward') {
|
||||
log('skip: ', seconds, type);
|
||||
return __internal_audio_element.subscribe((el) => {
|
||||
if (!el) return warn('no audio element');
|
||||
if (type === 'backward') {
|
||||
el.currentTime = clamp(0, el.duration, el.currentTime - seconds);
|
||||
} else {
|
||||
el.currentTime = clamp(0, el.duration, el.currentTime + seconds);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
export const audio = {
|
||||
subscribe: state.subscribe,
|
||||
play,
|
||||
pause,
|
||||
mute,
|
||||
unmute,
|
||||
load,
|
||||
unload,
|
||||
setPlaybackRate,
|
||||
seek,
|
||||
skip,
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
export type PlayerElement = HTMLAudioElement | undefined;
|
||||
|
||||
export type PlayerMetadata = {
|
||||
duration: number;
|
||||
muted: boolean;
|
||||
paused: boolean;
|
||||
playbackRate: number;
|
||||
loading: boolean;
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
export function isBoolean(value: any): value is boolean {
|
||||
return typeof value === 'boolean';
|
||||
}
|
||||
|
||||
export function isNumber(value: any): value is number {
|
||||
return typeof value === 'number' && !isNaN(value);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
function section(t: number) {
|
||||
if (t < 10) return `0${t}`;
|
||||
return t;
|
||||
}
|
||||
|
||||
export function secondsToTimestamp(seconds: number) {
|
||||
const hh = Math.floor(seconds / 3600);
|
||||
const hh_remainder = seconds % 3600;
|
||||
const mm = Math.floor(hh_remainder / 60);
|
||||
const mm_remainder = hh_remainder % 60;
|
||||
const ss = Math.floor(mm_remainder);
|
||||
|
||||
const hrs = hh > 0 ? `${section(hh)}:` : '';
|
||||
const mins = mm ? `${section(mm)}:` : '00:';
|
||||
const secs = ss ? `${section(ss)}` : '00';
|
||||
|
||||
return `${hrs}${mins}${secs}`;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { AudioManager } from '$lib/components/audio';
|
||||
</script>
|
||||
|
||||
<AudioManager />
|
||||
|
||||
<slot />
|
||||
+39
-34
@@ -1,52 +1,57 @@
|
||||
<script>
|
||||
import Audio from '$lib/components/audio.svelte';
|
||||
<script lang="ts">
|
||||
import { audio } from '$lib/components/audio';
|
||||
|
||||
let playbackRate = 1;
|
||||
let volume = 0.5;
|
||||
let paused = true;
|
||||
const sources = {
|
||||
syntax: '/example-syntax.mp3',
|
||||
knomii: '/example-knomii.mp3',
|
||||
} as const;
|
||||
|
||||
let currentTime = 0;
|
||||
let current_time = 0;
|
||||
$: current_time = $audio.current_time;
|
||||
</script>
|
||||
|
||||
<h1>Demo</h1>
|
||||
<pre>{JSON.stringify($audio, null, 3)}</pre>
|
||||
|
||||
<h5>Native audio controls</h5>
|
||||
<Audio
|
||||
on:progress={(e) => console.log(e.detail)}
|
||||
src="/example.mp3"
|
||||
autoplay={false}
|
||||
{volume}
|
||||
{playbackRate}
|
||||
{paused}
|
||||
bind:currentTime
|
||||
let:duration
|
||||
>
|
||||
<progress data-paused={paused ? 'true' : 'false'} max={duration} value={currentTime} />
|
||||
<h1>Demo</h1>
|
||||
<a href="/another-page">Another Page</a>
|
||||
|
||||
<h5>Load Audio</h5>
|
||||
<button type="button" on:click={() => audio.load(sources['syntax'])}>Syntax</button>
|
||||
<button type="button" on:click={() => audio.load(sources['knomii'])}>Knomii</button>
|
||||
<button type="button" on:click={() => audio.unload()}>None</button>
|
||||
|
||||
<h5>Custom audio controls</h5>
|
||||
|
||||
<h6>Play / Pause Actions</h6>
|
||||
|
||||
<button type="button" on:click={() => audio.play()}>Play</button>
|
||||
<button type="button" on:click={() => audio.pause()}>Pause</button>
|
||||
<button type="button" on:click={() => audio.pause('toggle')}>Toggle</button>
|
||||
|
||||
<h6>Audio Actions</h6>
|
||||
|
||||
<button type="button" on:click={() => (paused = false)}>Play</button>
|
||||
<button type="button" on:click={() => (paused = true)}>Pause</button>
|
||||
<button type="button" on:click={() => (paused = !paused)}>Toggle</button>
|
||||
<button type="button" on:click={() => audio.mute()}>Mute</button>
|
||||
<button type="button" on:click={() => audio.unmute()}>Unmute</button>
|
||||
<button type="button" on:click={() => audio.mute('toggle')}>Toggle</button>
|
||||
|
||||
<h6>Seeking</h6>
|
||||
|
||||
<button type="button" on:click={() => (currentTime = currentTime + 5)}>Skip 5s</button>
|
||||
<button type="button" on:click={() => (currentTime = currentTime - 5)}>Rewind 5s</button>
|
||||
<button type="button" on:click={() => (currentTime = 30)}>Go to 30s</button>
|
||||
<button type="button" on:click={() => (currentTime = duration - 30)}>Go to 30s before end</button>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={$audio.duration}
|
||||
style="width:100%"
|
||||
bind:value={current_time}
|
||||
on:change={(e) => audio.seek(parseInt(e.currentTarget.value))}
|
||||
/>
|
||||
|
||||
<button type="button" on:click={() => audio.seek(30)}>Go to 30s from start </button>
|
||||
<button type="button" on:click={() => audio.seek(30, 'from-end')}>Go to 30s from end</button>
|
||||
<button type="button" on:click={() => audio.skip(10, 'forward')}>Skip 10s</button>
|
||||
<button type="button" on:click={() => audio.skip(10, 'backward')}>Rewind 10s</button>
|
||||
|
||||
<h6>Playback Rate</h6>
|
||||
|
||||
{#each [0.5, 1, 2, 3] as rate}
|
||||
<button type="button" on:click={() => (playbackRate = rate)}>{rate}x</button>
|
||||
<button type="button" on:click={() => audio.setPlaybackRate(rate)}>{rate}x</button>
|
||||
{/each}
|
||||
|
||||
<h6>Volume</h6>
|
||||
|
||||
{#each [0, 0.25, 0.5, 0.75, 1] as v}
|
||||
<button type="button" on:click={() => (volume = v)}>{v * 100}%</button>
|
||||
{/each}
|
||||
</Audio>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { audio } from '$lib/components/audio';
|
||||
|
||||
const sources = {
|
||||
syntax: '/example-syntax.mp3',
|
||||
knomii: '/example-knomii.mp3',
|
||||
} as const;
|
||||
|
||||
let current_time = 0;
|
||||
$: current_time = $audio.current_time;
|
||||
</script>
|
||||
|
||||
<h1>Demo</h1>
|
||||
|
||||
<a href="/">Demo</a>
|
||||
|
||||
<pre>{JSON.stringify($audio, null, 3)}</pre>
|
||||
Binary file not shown.
@@ -1905,6 +1905,11 @@ jsonfile@^4.0.0:
|
||||
optionalDependencies:
|
||||
graceful-fs "^4.1.6"
|
||||
|
||||
just-clamp@^4.2.0:
|
||||
version "4.2.0"
|
||||
resolved "https://registry.yarnpkg.com/just-clamp/-/just-clamp-4.2.0.tgz#4dafc300d2f44685082b686f13deaa84d1c53b21"
|
||||
integrity sha512-ssHiAxuN7R+VP7jS1XyUP7ju5YC4bTQwQdzYtuZkASTrKe9KsI/X0t+5BJeD6Un6z/dNMDFVNQpQEgUphpXa0w==
|
||||
|
||||
kind-of@^6.0.3:
|
||||
version "6.0.3"
|
||||
resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd"
|
||||
|
||||
Reference in New Issue
Block a user