feat(ui): persistent cross-navigation audio player with expanded controls

- Add audio.svelte.ts: module singleton AudioStore (Svelte 5 runes) with
  slug/chapter/title metadata, status, progress, playback state, and
  toggleRequest/seekRequest signals for layout<->audio element communication
- Rewrite AudioPlayer.svelte as a store controller: no <audio> element owned;
  drives audioStore for presign->generate->play flow; shows inline controls
  when current chapter is active, 'Now playing / Load this chapter' banner
  when a different chapter is playing
- Update +layout.svelte: single persistent <audio> outside {#key} block so
  it never unmounts on navigation; effects to load URL, sync speed, handle
  toggle/seek requests; fixed bottom mini-player bar with seek, skip 15s/30s,
  speed cycle, go-to-chapter link, dismiss; pb-24 padding when active
- Pass chapterTitle and bookTitle from chapter page to AudioPlayer
This commit is contained in:
Admin
2026-03-04 15:34:56 +05:00
parent 0d7b985469
commit 034e670795
4 changed files with 486 additions and 162 deletions

View File

@@ -1,70 +1,63 @@
<script lang="ts">
/**
* AudioPlayer — single-button audio player.
* AudioPlayer — controller component.
*
* On click:
* 1. Try GET /api/presign/audio — if 200, load and play.
* 2. If 404, POST /api/audio/:slug/:n to generate. While generating, show
* a pseudo progress bar that starts slow, accelerates, then slows near
* 80 %. When generation resolves, the bar jumps to 100 % and audio plays.
* Does NOT own an <audio> element. Instead it reads/writes `audioStore`,
* which is shared with the layout's persistent <audio> element so audio
* survives SvelteKit navigations.
*
* On "Play narration" click:
* 1. Populate store metadata (slug, chapter, titles, voice, speed).
* 2. Try GET /api/presign/audio — if 200, set audioUrl → layout plays.
* 3. If 404, POST /api/audio/:slug/:n to generate. Drive pseudo progress bar
* via audioStore.progress. On success, presign again and set audioUrl.
*
* When the same chapter is already loaded/playing: show inline playback state.
* When a different chapter is playing: show "Now playing Ch.X" with a
* "Load this chapter" button.
*/
import { audioStore } from '$lib/audio.svelte';
interface Props {
slug: string;
chapter: number;
chapterTitle?: string;
bookTitle?: string;
voice?: string;
speed?: number;
}
let { slug, chapter, voice = 'af_bella', speed = 1.0 }: Props = $props();
let {
slug,
chapter,
chapterTitle = '',
bookTitle = '',
voice = 'af_bella',
speed = 1.0
}: Props = $props();
type Status = 'idle' | 'loading' | 'generating' | 'ready' | 'error';
let status = $state<Status>('idle');
let audioUrl = $state('');
let errorMsg = $state('');
let audioEl = $state<HTMLAudioElement | null>(null);
let currentTime = $state(0);
let duration = $state(0);
let isPlaying = $state(false);
// Pseudo progress bar — value 0-100.
let progress = $state(0);
// ── Pseudo progress helpers ────────────────────────────────────────────────
let progressRafId = 0;
// ── Pseudo progress animation ────────────────────────────────────────────
// Eases in to ~80 % slowly, stalls, then can be forced to 100 % externally.
function startProgress() {
progress = 0;
audioStore.progress = 0;
let last = performance.now();
function tick(now: number) {
const dt = (now - last) / 1000; // seconds
const dt = (now - last) / 1000;
last = now;
// Speed profile:
// 0 30 % → 4 %/s (slow start)
// 30 60 % → 12 %/s (ramp up)
// 60 80 % → 4 %/s (slow down)
// 80 99 % → 0.3 %/s (crawl, never quite reaches 100)
let rate: number;
if (progress < 30) {
rate = 4;
} else if (progress < 60) {
rate = 12;
} else if (progress < 80) {
rate = 4;
} else {
rate = 0.3;
}
if (audioStore.progress < 30) rate = 4;
else if (audioStore.progress < 60) rate = 12;
else if (audioStore.progress < 80) rate = 4;
else rate = 0.3;
progress = Math.min(progress + rate * dt, 99);
if (progress < 99) {
audioStore.progress = Math.min(audioStore.progress + rate * dt, 99);
if (audioStore.progress < 99) {
progressRafId = requestAnimationFrame(tick);
}
}
progressRafId = requestAnimationFrame(tick);
}
@@ -77,20 +70,18 @@
async function finishProgress() {
stopProgress();
// Animate quickly to 100 %.
const step = () => {
progress = Math.min(progress + 8, 100);
if (progress < 100) {
audioStore.progress = Math.min(audioStore.progress + 8, 100);
if (audioStore.progress < 100) {
progressRafId = requestAnimationFrame(step);
}
};
progressRafId = requestAnimationFrame(step);
// Wait for the short fill animation to look good.
await new Promise((r) => setTimeout(r, 200));
stopProgress();
}
// ── Core logic ────────────────────────────────────────────────────────────
// ── API helpers ────────────────────────────────────────────────────────────
async function tryPresign(): Promise<string | null> {
const params = new URLSearchParams({
@@ -106,28 +97,30 @@
return data.url;
}
async function handlePlay() {
if (status === 'ready' && audioUrl) {
togglePlay();
return;
}
// ── Core play flow ─────────────────────────────────────────────────────────
status = 'loading';
errorMsg = '';
async function startPlayback() {
// Populate store metadata so layout + mini-bar have track info.
audioStore.slug = slug;
audioStore.chapter = chapter;
audioStore.chapterTitle = chapterTitle;
audioStore.bookTitle = bookTitle;
audioStore.voice = voice;
audioStore.speed = speed;
audioStore.status = 'loading';
audioStore.errorMsg = '';
try {
// Fast path: audio already exists.
// Fast path: audio already in MinIO.
const url = await tryPresign();
if (url) {
audioUrl = url;
status = 'ready';
// Auto-play once metadata loads.
requestAnimationFrame(() => audioEl?.play());
audioStore.audioUrl = url;
audioStore.status = 'ready';
return;
}
// Slow path: trigger generation.
status = 'generating';
// Slow path: trigger Kokoro generation.
audioStore.status = 'generating';
startProgress();
const res = await fetch(`/api/audio/${slug}/${chapter}`, {
@@ -137,141 +130,159 @@
});
if (!res.ok) throw new Error(`Generation failed: HTTP ${res.status}`);
// Generation succeeded — fill the bar to 100 % then load.
await finishProgress();
const url2 = await tryPresign();
if (!url2) throw new Error('Audio generated but presign returned 404');
audioUrl = url2;
status = 'ready';
requestAnimationFrame(() => audioEl?.play());
audioStore.audioUrl = url2;
audioStore.status = 'ready';
} catch (e) {
stopProgress();
progress = 0;
status = 'error';
errorMsg = String(e);
audioStore.progress = 0;
audioStore.status = 'error';
audioStore.errorMsg = String(e);
}
}
async function handlePlay() {
const isCurrent = audioStore.isCurrentChapter(slug, chapter);
// Already loaded this chapter: toggle play/pause.
if (isCurrent && audioStore.status === 'ready') {
// The layout owns the audio element; we signal via a store flag.
// We don't have a direct reference here — the layout toggles on its own.
// Dispatch a custom event that the layout can listen to, or simply
// expose a toggle helper on the store (simplest: use a counter).
audioStore.toggleRequest = (audioStore.toggleRequest ?? 0) + 1;
return;
}
// Not yet loaded — start the full flow.
await startPlayback();
}
function formatTime(s: number): string {
if (!isFinite(s) || s < 0) return '0:00';
const m = Math.floor(s / 60);
const sec = Math.floor(s % 60);
return `${m}:${sec.toString().padStart(2, '0')}`;
}
function togglePlay() {
if (!audioEl) return;
if (isPlaying) {
audioEl.pause();
} else {
audioEl.play();
}
}
function seek(e: Event) {
if (!audioEl) return;
const input = e.target as HTMLInputElement;
audioEl.currentTime = parseFloat(input.value);
}
</script>
<div class="mt-6 p-4 rounded-lg bg-zinc-800 border border-zinc-700">
<div class="flex items-center gap-2 mb-3">
<svg class="w-4 h-4 text-amber-400" fill="currentColor" viewBox="0 0 24 24">
<path d="M11.536 3.464a5 5 0 010 7.072L8 14H5v3H2V7h3l3.536-3.536a5 5 0 017.072 0l-4.072 4.072zM19 8a1 1 0 011 1v6a1 1 0 01-2 0V9a1 1 0 011-1zm-4-2a1 1 0 011 1v10a1 1 0 01-2 0V7a1 1 0 011-1z"/>
<path d="M12 3v10.55A4 4 0 1014 17V7h4V3h-6z"/>
</svg>
<span class="text-sm text-zinc-300 font-medium">Audio Narration</span>
</div>
{#if status === 'idle' || status === 'loading'}
<button
onclick={handlePlay}
disabled={status === 'loading'}
class="px-4 py-1.5 rounded bg-amber-400 text-zinc-900 text-sm font-semibold hover:bg-amber-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
>
{#if status === 'loading'}
{#if audioStore.isCurrentChapter(slug, chapter)}
<!-- ── This chapter is the active one ── -->
{#if audioStore.status === 'idle' || audioStore.status === 'error'}
<!-- Should not normally reach here while current, but handle gracefully -->
{#if audioStore.status === 'error'}
<p class="text-red-400 text-sm mb-2">{audioStore.errorMsg || 'Failed to load audio.'}</p>
{/if}
<button
onclick={handlePlay}
class="px-4 py-1.5 rounded bg-amber-400 text-zinc-900 text-sm font-semibold hover:bg-amber-300 transition-colors flex items-center gap-2"
>
<svg class="w-3.5 h-3.5 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</svg>
Play narration
</button>
{:else if audioStore.status === 'loading'}
<button
disabled
class="px-4 py-1.5 rounded bg-amber-400 text-zinc-900 text-sm font-semibold opacity-50 cursor-not-allowed flex items-center gap-2"
>
<svg class="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
</svg>
{:else}
<svg class="w-3.5 h-3.5 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</svg>
{/if}
Play narration
</button>
{:else if status === 'generating'}
<!-- Pseudo progress bar while Kokoro generates audio -->
<div class="space-y-2">
<p class="text-xs text-zinc-400">Generating narration…</p>
<div class="w-full h-1.5 bg-zinc-700 rounded-full overflow-hidden">
<div
class="h-full bg-amber-400 rounded-full transition-none"
style="width: {progress}%"
></div>
</div>
<p class="text-xs text-zinc-500 tabular-nums">{Math.round(progress)} %</p>
</div>
{:else if status === 'error'}
<div class="text-red-400 text-sm">
<p>{errorMsg || 'Failed to load audio.'}</p>
<button
onclick={() => { status = 'idle'; errorMsg = ''; }}
class="mt-1 text-xs underline text-zinc-400 hover:text-zinc-200"
>
Dismiss
Loading…
</button>
</div>
{:else if status === 'ready' && audioUrl}
<!-- Native audio element (hidden, controlled by custom UI) -->
<audio
bind:this={audioEl}
src={audioUrl}
bind:currentTime
bind:duration
onplay={() => (isPlaying = true)}
onpause={() => (isPlaying = false)}
onended={() => (isPlaying = false)}
preload="metadata"
></audio>
<!-- Custom controls -->
<div class="flex flex-col gap-2">
<div class="flex items-center gap-3">
<button
onclick={togglePlay}
class="w-9 h-9 rounded-full bg-amber-400 text-zinc-900 flex items-center justify-center hover:bg-amber-300 transition-colors flex-shrink-0"
aria-label={isPlaying ? 'Pause' : 'Play'}
>
{#if isPlaying}
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
</svg>
{:else}
<svg class="w-4 h-4 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</svg>
{/if}
</button>
<span class="text-xs text-zinc-400 w-20 flex-shrink-0">
{formatTime(currentTime)} / {formatTime(duration || 0)}
</span>
{:else if audioStore.status === 'generating'}
<div class="space-y-2">
<p class="text-xs text-zinc-400">Generating narration…</p>
<div class="w-full h-1.5 bg-zinc-700 rounded-full overflow-hidden">
<div
class="h-full bg-amber-400 rounded-full transition-none"
style="width: {audioStore.progress}%"
></div>
</div>
<p class="text-xs text-zinc-500 tabular-nums">{Math.round(audioStore.progress)}%</p>
</div>
{:else if audioStore.status === 'ready'}
<!-- Inline full-size controls (larger than the mini-bar) -->
<div class="flex flex-col gap-2">
<!-- Seek bar -->
<input
type="range"
min="0"
max={duration || 0}
value={currentTime}
oninput={seek}
class="flex-1 accent-amber-400 h-1.5 rounded"
max={audioStore.duration || 0}
value={audioStore.currentTime}
oninput={(e) => {
audioStore.seekRequest = parseFloat((e.target as HTMLInputElement).value);
}}
class="w-full accent-amber-400 h-1.5 rounded cursor-pointer"
/>
<div class="flex items-center gap-3">
<!-- Play/Pause -->
<button
onclick={handlePlay}
class="w-9 h-9 rounded-full bg-amber-400 text-zinc-900 flex items-center justify-center hover:bg-amber-300 transition-colors flex-shrink-0"
aria-label={audioStore.isPlaying ? 'Pause' : 'Play'}
>
{#if audioStore.isPlaying}
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
</svg>
{:else}
<svg class="w-4 h-4 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</svg>
{/if}
</button>
<span class="text-xs text-zinc-400 tabular-nums">
{formatTime(audioStore.currentTime)} / {formatTime(audioStore.duration)}
</span>
</div>
</div>
{/if}
{:else if audioStore.active}
<!-- ── A different chapter is currently playing ── -->
<div class="flex items-center justify-between gap-3">
<p class="text-xs text-zinc-400">
Now playing: {audioStore.chapterTitle || `Ch.${audioStore.chapter}`}
</p>
<button
onclick={startPlayback}
class="px-3 py-1 rounded bg-zinc-700 text-zinc-200 text-xs font-medium hover:bg-zinc-600 transition-colors flex-shrink-0"
>
Load this chapter
</button>
</div>
{:else}
<!-- ── Idle — nothing playing ── -->
<button
onclick={handlePlay}
class="px-4 py-1.5 rounded bg-amber-400 text-zinc-900 text-sm font-semibold hover:bg-amber-300 transition-colors flex items-center gap-2"
>
<svg class="w-3.5 h-3.5 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
<path d="M8 5v14l11-7z"/>
</svg>
Play narration
</button>
{/if}
</div>