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:
@@ -1,10 +1,12 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* AudioPlayer — fetches a presigned MinIO URL for the chapter audio
|
||||
* and renders a native <audio> element with custom controls.
|
||||
* AudioPlayer — single-button audio player.
|
||||
*
|
||||
* The audio is generated server-side by Kokoro and cached.
|
||||
* If no audio exists yet, the user can trigger generation via the scraper API.
|
||||
* 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.
|
||||
*/
|
||||
|
||||
interface Props {
|
||||
@@ -16,7 +18,7 @@
|
||||
|
||||
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 audioUrl = $state('');
|
||||
@@ -26,46 +28,128 @@
|
||||
let duration = $state(0);
|
||||
let isPlaying = $state(false);
|
||||
|
||||
async function loadAudio() {
|
||||
status = 'loading';
|
||||
errorMsg = '';
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
slug,
|
||||
n: String(chapter),
|
||||
voice,
|
||||
speed: String(speed)
|
||||
});
|
||||
const res = await fetch(`/api/presign/audio?${params.toString()}`);
|
||||
if (res.status === 404) {
|
||||
status = 'idle';
|
||||
return;
|
||||
// Pseudo progress bar — value 0-100.
|
||||
let progress = $state(0);
|
||||
let progressRafId = 0;
|
||||
|
||||
// ── Pseudo progress animation ────────────────────────────────────────────
|
||||
// Eases in to ~80 % slowly, stalls, then can be forced to 100 % externally.
|
||||
function startProgress() {
|
||||
progress = 0;
|
||||
let last = performance.now();
|
||||
|
||||
function tick(now: number) {
|
||||
const dt = (now - last) / 1000; // seconds
|
||||
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 (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = (await res.json()) as { url: string };
|
||||
audioUrl = data.url;
|
||||
status = 'ready';
|
||||
} catch (e) {
|
||||
status = 'error';
|
||||
errorMsg = String(e);
|
||||
|
||||
progress = Math.min(progress + rate * dt, 99);
|
||||
|
||||
if (progress < 99) {
|
||||
progressRafId = requestAnimationFrame(tick);
|
||||
}
|
||||
}
|
||||
|
||||
progressRafId = requestAnimationFrame(tick);
|
||||
}
|
||||
|
||||
function stopProgress() {
|
||||
if (progressRafId) {
|
||||
cancelAnimationFrame(progressRafId);
|
||||
progressRafId = 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function generateAudio() {
|
||||
status = 'generating';
|
||||
errorMsg = '';
|
||||
try {
|
||||
const res = await fetch(`/api/audio/${slug}/${chapter}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ voice, speed })
|
||||
async function finishProgress() {
|
||||
stopProgress();
|
||||
// Animate quickly to 100 %.
|
||||
const step = () => {
|
||||
progress = Math.min(progress + 8, 100);
|
||||
if (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 ────────────────────────────────────────────────────────────
|
||||
|
||||
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}`);
|
||||
// After generation, fetch the presigned URL
|
||||
await loadAudio();
|
||||
const res = await fetch(`/api/presign/audio?${params}`);
|
||||
if (res.status === 404) return null;
|
||||
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) {
|
||||
stopProgress();
|
||||
progress = 0;
|
||||
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>
|
||||
</div>
|
||||
|
||||
{#if status === 'idle'}
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
onclick={loadAudio}
|
||||
class="px-3 py-1.5 rounded bg-zinc-700 text-zinc-300 text-sm hover:bg-zinc-600 transition-colors"
|
||||
>
|
||||
Check for audio
|
||||
</button>
|
||||
<button
|
||||
onclick={generateAudio}
|
||||
class="px-3 py-1.5 rounded bg-amber-400 text-zinc-900 text-sm font-semibold hover:bg-amber-300 transition-colors"
|
||||
>
|
||||
Generate audio
|
||||
</button>
|
||||
</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'}
|
||||
<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 === 'loading' || status === 'generating'}
|
||||
<div class="flex items-center gap-2 text-zinc-400 text-sm">
|
||||
<svg class="w-4 h-4 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>
|
||||
{status === 'generating' ? 'Generating audio (this may take a few minutes)…' : 'Loading…'}
|
||||
{: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'; }}
|
||||
onclick={() => { status = 'idle'; errorMsg = ''; }}
|
||||
class="mt-1 text-xs underline text-zinc-400 hover:text-zinc-200"
|
||||
>
|
||||
Dismiss
|
||||
@@ -150,7 +241,6 @@
|
||||
|
||||
<!-- Custom controls -->
|
||||
<div class="flex flex-col gap-2">
|
||||
<!-- Play/pause + time -->
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
onclick={togglePlay}
|
||||
|
||||
Reference in New Issue
Block a user