feat(ui): replace two-button audio UI with single smart play button and pseudo progress bar

- Single 'Play narration' button: checks presign first, plays immediately if audio exists, otherwise triggers generation
- During generation shows an animated pseudo progress bar: slow start (4%/s) → accelerates (12%/s at 30%) → slows near 80% (4%/s) → crawls to 99% (0.3%/s)
- When generation completes, bar jumps to 100% then transitions to audio player
- Auto-plays audio after generation completes
This commit is contained in:
Admin
2026-03-04 15:15:23 +05:00
parent 11a846d043
commit 53af7515a3

View File

@@ -1,10 +1,12 @@
<script lang="ts"> <script lang="ts">
/** /**
* AudioPlayer — fetches a presigned MinIO URL for the chapter audio * AudioPlayer — single-button audio player.
* and renders a native <audio> element with custom controls.
* *
* The audio is generated server-side by Kokoro and cached. * On click:
* If no audio exists yet, the user can trigger generation via the scraper API. * 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.
*/ */
interface Props { interface Props {
@@ -16,7 +18,7 @@
let { slug, chapter, voice = 'af_bella', speed = 1.0 }: Props = $props(); let { slug, chapter, voice = 'af_bella', speed = 1.0 }: Props = $props();
type Status = 'idle' | 'loading' | 'ready' | 'error' | 'generating'; type Status = 'idle' | 'loading' | 'generating' | 'ready' | 'error';
let status = $state<Status>('idle'); let status = $state<Status>('idle');
let audioUrl = $state(''); let audioUrl = $state('');
@@ -26,46 +28,128 @@
let duration = $state(0); let duration = $state(0);
let isPlaying = $state(false); let isPlaying = $state(false);
async function loadAudio() { // Pseudo progress bar — value 0-100.
status = 'loading'; let progress = $state(0);
errorMsg = ''; let progressRafId = 0;
try {
const params = new URLSearchParams({ // ── Pseudo progress animation ────────────────────────────────────────────
slug, // Eases in to ~80 % slowly, stalls, then can be forced to 100 % externally.
n: String(chapter), function startProgress() {
voice, progress = 0;
speed: String(speed) let last = performance.now();
});
const res = await fetch(`/api/presign/audio?${params.toString()}`); function tick(now: number) {
if (res.status === 404) { const dt = (now - last) / 1000; // seconds
status = 'idle'; last = now;
return;
// 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 (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = (await res.json()) as { url: string }; progress = Math.min(progress + rate * dt, 99);
audioUrl = data.url;
status = 'ready'; if (progress < 99) {
} catch (e) { progressRafId = requestAnimationFrame(tick);
status = 'error'; }
errorMsg = String(e); }
progressRafId = requestAnimationFrame(tick);
}
function stopProgress() {
if (progressRafId) {
cancelAnimationFrame(progressRafId);
progressRafId = 0;
} }
} }
async function generateAudio() { async function finishProgress() {
status = 'generating'; stopProgress();
errorMsg = ''; // Animate quickly to 100 %.
try { const step = () => {
const res = await fetch(`/api/audio/${slug}/${chapter}`, { progress = Math.min(progress + 8, 100);
method: 'POST', if (progress < 100) {
headers: { 'Content-Type': 'application/json' }, progressRafId = requestAnimationFrame(step);
body: JSON.stringify({ voice, speed }) }
};
progressRafId = requestAnimationFrame(step);
// Wait for the short fill animation to look good.
await new Promise((r) => setTimeout(r, 200));
stopProgress();
}
// ── Core logic ────────────────────────────────────────────────────────────
async function tryPresign(): Promise<string | null> {
const params = new URLSearchParams({
slug,
n: String(chapter),
voice,
speed: String(speed)
}); });
if (!res.ok) throw new Error(`Generation failed: ${res.status}`); const res = await fetch(`/api/presign/audio?${params}`);
// After generation, fetch the presigned URL if (res.status === 404) return null;
await loadAudio(); if (!res.ok) throw new Error(`presign HTTP ${res.status}`);
const data = (await res.json()) as { url: string };
return data.url;
}
async function handlePlay() {
if (status === 'ready' && audioUrl) {
togglePlay();
return;
}
status = 'loading';
errorMsg = '';
try {
// Fast path: audio already exists.
const url = await tryPresign();
if (url) {
audioUrl = url;
status = 'ready';
// Auto-play once metadata loads.
requestAnimationFrame(() => audioEl?.play());
return;
}
// Slow path: trigger generation.
status = 'generating';
startProgress();
const res = await fetch(`/api/audio/${slug}/${chapter}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ voice, speed })
});
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());
} catch (e) { } catch (e) {
stopProgress();
progress = 0;
status = 'error'; status = 'error';
errorMsg = `Generation failed: ${e}`; errorMsg = String(e);
} }
} }
@@ -99,36 +183,43 @@
<span class="text-sm text-zinc-300 font-medium">Audio Narration</span> <span class="text-sm text-zinc-300 font-medium">Audio Narration</span>
</div> </div>
{#if status === 'idle'} {#if status === 'idle' || status === 'loading'}
<div class="flex gap-2"> <button
<button onclick={handlePlay}
onclick={loadAudio} disabled={status === 'loading'}
class="px-3 py-1.5 rounded bg-zinc-700 text-zinc-300 text-sm hover:bg-zinc-600 transition-colors" 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"
> >
Check for audio {#if status === 'loading'}
</button> <svg class="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24">
<button <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
onclick={generateAudio} <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
class="px-3 py-1.5 rounded bg-amber-400 text-zinc-900 text-sm font-semibold hover:bg-amber-300 transition-colors" </svg>
> {:else}
Generate audio <svg class="w-3.5 h-3.5 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
</button> <path d="M8 5v14l11-7z"/>
</div> </svg>
{/if}
Play narration
</button>
{:else if status === 'loading' || status === 'generating'} {:else if status === 'generating'}
<div class="flex items-center gap-2 text-zinc-400 text-sm"> <!-- Pseudo progress bar while Kokoro generates audio -->
<svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"> <div class="space-y-2">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> <p class="text-xs text-zinc-400">Generating narration…</p>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path> <div class="w-full h-1.5 bg-zinc-700 rounded-full overflow-hidden">
</svg> <div
{status === 'generating' ? 'Generating audio (this may take a few minutes)…' : 'Loading…'} 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> </div>
{:else if status === 'error'} {:else if status === 'error'}
<div class="text-red-400 text-sm"> <div class="text-red-400 text-sm">
<p>{errorMsg || 'Failed to load audio.'}</p> <p>{errorMsg || 'Failed to load audio.'}</p>
<button <button
onclick={() => { status = 'idle'; }} onclick={() => { status = 'idle'; errorMsg = ''; }}
class="mt-1 text-xs underline text-zinc-400 hover:text-zinc-200" class="mt-1 text-xs underline text-zinc-400 hover:text-zinc-200"
> >
Dismiss Dismiss
@@ -150,7 +241,6 @@
<!-- Custom controls --> <!-- Custom controls -->
<div class="flex flex-col gap-2"> <div class="flex flex-col gap-2">
<!-- Play/pause + time -->
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<button <button
onclick={togglePlay} onclick={togglePlay}