feat(ui): add audio player component, presign API route, and reading progress tracking
This commit is contained in:
187
ui/src/lib/components/AudioPlayer.svelte
Normal file
187
ui/src/lib/components/AudioPlayer.svelte
Normal 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>
|
||||
26
ui/src/routes/api/presign/audio/+server.ts
Normal file
26
ui/src/routes/api/presign/audio/+server.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { presignAudio } from '$lib/server/minio';
|
||||
|
||||
/**
|
||||
* GET /api/presign/audio?slug=...&n=...&voice=...&speed=...
|
||||
* Returns a presigned MinIO URL for the audio file so the browser
|
||||
* can stream it directly without going through the server.
|
||||
*/
|
||||
export const GET: RequestHandler = async ({ url }) => {
|
||||
const slug = url.searchParams.get('slug');
|
||||
const n = parseInt(url.searchParams.get('n') ?? '', 10);
|
||||
const voice = url.searchParams.get('voice') ?? undefined;
|
||||
const speed = parseFloat(url.searchParams.get('speed') ?? '1') || 1;
|
||||
|
||||
if (!slug || !n || n < 1) {
|
||||
error(400, 'Missing slug or n');
|
||||
}
|
||||
|
||||
try {
|
||||
const presignedUrl = await presignAudio(slug, n, voice, speed);
|
||||
return json({ url: presignedUrl });
|
||||
} catch (e) {
|
||||
error(500, `Could not get presigned URL: ${e}`);
|
||||
}
|
||||
};
|
||||
19
ui/src/routes/api/progress/+server.ts
Normal file
19
ui/src/routes/api/progress/+server.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { setProgress } from '$lib/server/pocketbase';
|
||||
|
||||
/**
|
||||
* POST /api/progress
|
||||
* Body: { slug: string, chapter: number }
|
||||
* Records the user's reading position for the current session.
|
||||
*/
|
||||
export const POST: RequestHandler = async ({ request, locals }) => {
|
||||
const body = await request.json().catch(() => null);
|
||||
|
||||
if (!body || typeof body.slug !== 'string' || typeof body.chapter !== 'number') {
|
||||
error(400, 'Invalid body — expected { slug, chapter }');
|
||||
}
|
||||
|
||||
await setProgress(locals.sessionId, body.slug, body.chapter);
|
||||
return json({ ok: true });
|
||||
};
|
||||
@@ -1,7 +1,22 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import AudioPlayer from '$lib/components/AudioPlayer.svelte';
|
||||
import type { PageData } from './$types';
|
||||
|
||||
let { data }: { data: PageData } = $props();
|
||||
|
||||
// Record reading progress when the chapter is opened
|
||||
onMount(async () => {
|
||||
try {
|
||||
await fetch('/api/progress', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ slug: data.book.slug, chapter: data.chapter.number })
|
||||
});
|
||||
} catch {
|
||||
// Non-critical — silently ignore
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
@@ -41,7 +56,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Chapter heading -->
|
||||
<div class="mb-8">
|
||||
<div class="mb-6">
|
||||
<p class="text-zinc-500 text-sm mb-1">Chapter {data.chapter.number}</p>
|
||||
<h1 class="text-xl font-bold text-zinc-100">
|
||||
{data.chapter.title || `Chapter ${data.chapter.number}`}
|
||||
@@ -51,13 +66,16 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Audio player -->
|
||||
<AudioPlayer slug={data.book.slug} chapter={data.chapter.number} />
|
||||
|
||||
<!-- Chapter content -->
|
||||
{#if !data.html}
|
||||
<div class="text-zinc-500 text-center py-16">
|
||||
<p>Chapter content not available.</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="prose-chapter">
|
||||
<div class="prose-chapter mt-8">
|
||||
{@html data.html}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
Reference in New Issue
Block a user