feat(ui): add audio player component, presign API route, and reading progress tracking

This commit is contained in:
Admin
2026-03-02 21:41:20 +05:00
parent 6bf79ab392
commit 4f84bd29c9
4 changed files with 252 additions and 2 deletions

View File

@@ -0,0 +1,187 @@
<script lang="ts">
/**
* AudioPlayer — fetches a presigned MinIO URL for the chapter audio
* and renders a native <audio> element with custom controls.
*
* The audio is generated server-side by Kokoro and cached.
* If no audio exists yet, the user can trigger generation via the scraper API.
*/
interface Props {
slug: string;
chapter: number;
voice?: string;
speed?: number;
}
let { slug, chapter, voice = 'af_bella', speed = 1.0 }: Props = $props();
type Status = 'idle' | 'loading' | 'ready' | 'error' | 'generating';
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);
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;
}
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);
}
}
async function generateAudio() {
status = 'generating';
errorMsg = '';
try {
const res = await fetch(`http://localhost:8080/ui/audio/${slug}/${chapter}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ voice, speed })
});
if (!res.ok) throw new Error(`Generation failed: ${res.status}`);
// After generation, fetch the presigned URL
await loadAudio();
} catch (e) {
status = 'error';
errorMsg = `Generation failed: ${e}`;
}
}
function formatTime(s: number): string {
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"/>
</svg>
<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>
{: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…'}
</div>
{:else if status === 'error'}
<div class="text-red-400 text-sm">
<p>{errorMsg || 'Failed to load audio.'}</p>
<button
onclick={() => { status = 'idle'; }}
class="mt-1 text-xs underline text-zinc-400 hover:text-zinc-200"
>
Dismiss
</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">
<!-- Play/pause + time -->
<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>
<!-- Seek bar -->
<input
type="range"
min="0"
max={duration || 0}
value={currentTime}
oninput={seek}
class="flex-1 accent-amber-400 h-1.5 rounded"
/>
</div>
</div>
{/if}
</div>