Begun implementing playback

This commit is contained in:
Ben committed 2026-07-04 16:15:50 +02:00
1 parent 279e5ac34f
commit fa7375d0e9
9 files changed
+712 -49

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
import { useEffect, useRef, useState } from 'react'
import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props {
cols: WaveColumn[]
currentTime: number
duration: number
onSeek: (t: number) => void
}
const MIN_SEC = 2 // most zoomed-in (seconds across the view)
const MAX_SEC = 64 // most zoomed-out
const DEFAULT_SEC = 16
/**
* Traktor-style scrolling main waveform: the playhead is fixed at the centre and
* the waveform scrolls beneath it. Shows a time window [t - sec/2, t + sec/2];
* the zoom buttons change that window width. Repaints every frame (driven by the
* parent's rAF-updated currentTime).
*/
export function MainWaveform({ cols, currentTime, duration, onSeek }: Props) {
const wrapRef = useRef<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null)
const [secPerView, setSecPerView] = useState(DEFAULT_SEC)
// Draw closes over the latest props/state; a ref lets the ResizeObserver call
// the current version without re-subscribing.
const draw = () => {
const canvas = canvasRef.current
const wrap = wrapRef.current
if (!canvas || !wrap) return
const dpr = window.devicePixelRatio || 1
const w = Math.max(1, Math.floor(wrap.clientWidth * dpr))
const h = Math.max(1, Math.floor(wrap.clientHeight * dpr))
if (canvas.width !== w) canvas.width = w
if (canvas.height !== h) canvas.height = h
const ctx = canvas.getContext('2d')!
ctx.clearRect(0, 0, w, h)
if (cols.length && duration > 0) {
const half = secPerView / 2
const startFrac = (currentTime - half) / duration
const endFrac = (currentTime + half) / duration
paintWave(ctx, cols, w, h, startFrac, endFrac)
}
// Fixed centre playhead.
const cx = Math.floor(w / 2)
ctx.fillStyle = '#e6e9ef'
ctx.fillRect(cx, 0, Math.max(1, Math.round(dpr)), h)
}
const drawRef = useRef(draw)
drawRef.current = draw
// Redraw after every render (covers currentTime advancing, zoom, new track).
useEffect(() => {
draw()
})
useEffect(() => {
const wrap = wrapRef.current
if (!wrap) return
const ro = new ResizeObserver(() => drawRef.current())
ro.observe(wrap)
return () => ro.disconnect()
}, [])
// Click to seek: map horizontal offset from centre to a time delta.
const seek = (e: React.MouseEvent<HTMLDivElement>) => {
if (!duration) return
const rect = e.currentTarget.getBoundingClientRect()
const ratioFromCenter = (e.clientX - rect.left) / rect.width - 0.5
const t = currentTime + ratioFromCenter * secPerView
onSeek(Math.min(duration, Math.max(0, t)))
}
const zoomIn = () => setSecPerView((s) => Math.max(MIN_SEC, s / 2))
const zoomOut = () => setSecPerView((s) => Math.min(MAX_SEC, s * 2))
return (
<div ref={wrapRef} onClick={seek} className="relative h-full w-full cursor-pointer">
<canvas ref={canvasRef} className="block h-full w-full" />
{/* Zoom controls (Traktor-style +/-) */}
<div className="absolute right-2 top-2 flex flex-col gap-1">
<button
onClick={(e) => {
e.stopPropagation()
zoomIn()
}}
disabled={secPerView <= MIN_SEC}
className="flex h-6 w-6 items-center justify-center rounded border border-line bg-ink-950/70 text-sm text-text hover:border-accent disabled:opacity-30"
title="Zoom in"
>
+
</button>
<button
onClick={(e) => {
e.stopPropagation()
zoomOut()
}}
disabled={secPerView >= MAX_SEC}
className="flex h-6 w-6 items-center justify-center rounded border border-line bg-ink-950/70 text-sm text-text hover:border-accent disabled:opacity-30"
title="Zoom out"
>
−
</button>
</div>
</div>
)
}
@@ -0,0 +1,100 @@
import { useCallback, useEffect, useRef } from 'react'
import { paintWave, type WaveColumn } from '../lib/waveform'
interface Props {
cols: WaveColumn[]
currentTime: number
duration: number
onSeek: (t: number) => void
}
/**
* Whole-track overview waveform: static coloured waveform (cached to an
* offscreen canvas) with a moving playhead + dimmed played region. Click to
* seek anywhere in the track.
*/
export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props) {
const wrapRef = useRef<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null)
const cacheRef = useRef<HTMLCanvasElement | null>(null)
const timeRef = useRef(0)
const durRef = useRef(0)
const renderCache = useCallback(() => {
const canvas = canvasRef.current
if (!canvas || canvas.width === 0) return
let cache = cacheRef.current
if (!cache) {
cache = document.createElement('canvas')
cacheRef.current = cache
}
cache.width = canvas.width
cache.height = canvas.height
const ctx = cache.getContext('2d')!
ctx.clearRect(0, 0, cache.width, cache.height)
paintWave(ctx, cols, cache.width, cache.height, 0, 1)
}, [cols])
const draw = useCallback(() => {
const canvas = canvasRef.current
const cache = cacheRef.current
if (!canvas) return
const ctx = canvas.getContext('2d')!
const w = canvas.width
const h = canvas.height
ctx.clearRect(0, 0, w, h)
if (cache) ctx.drawImage(cache, 0, 0)
const dur = durRef.current
if (dur > 0) {
const px = Math.round((timeRef.current / dur) * w)
ctx.fillStyle = 'rgba(10,11,15,0.55)'
ctx.fillRect(0, 0, px, h)
ctx.fillStyle = '#e6e9ef'
ctx.fillRect(px, 0, 1, h)
}
}, [])
const resize = useCallback(() => {
const canvas = canvasRef.current
const wrap = wrapRef.current
if (!canvas || !wrap) return
const dpr = window.devicePixelRatio || 1
canvas.width = Math.max(1, Math.floor(wrap.clientWidth * dpr))
canvas.height = Math.max(1, Math.floor(wrap.clientHeight * dpr))
renderCache()
draw()
}, [renderCache, draw])
// Rebuild the cache when the columns change (new track) or on resize.
useEffect(() => {
resize()
}, [resize])
useEffect(() => {
const wrap = wrapRef.current
if (!wrap) return
const ro = new ResizeObserver(() => resize())
ro.observe(wrap)
return () => ro.disconnect()
}, [resize])
// Move the playhead as playback advances.
useEffect(() => {
timeRef.current = currentTime
durRef.current = duration
draw()
}, [currentTime, duration, draw])
const seek = (e: React.MouseEvent<HTMLDivElement>) => {
if (!duration) return
const rect = e.currentTarget.getBoundingClientRect()
const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width))
onSeek(ratio * duration)
}
return (
<div ref={wrapRef} onClick={seek} className="h-full w-full cursor-pointer">
<canvas ref={canvasRef} className="block h-full w-full" />
</div>
)
}
+197
View File
@@ -0,0 +1,197 @@
import { useEffect, useRef, useState } from 'react'
import { api, type Track } from '../api'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { MainWaveform } from './MainWaveform'
import { OverviewWaveform } from './OverviewWaveform'
interface Props {
/** The track currently loaded into the prep deck, if any. */
track: Track | null
onError?: (msg: string) => void
}
function fmt(secs: number): string {
if (!isFinite(secs) || secs < 0) return '0:00'
const m = Math.floor(secs / 60)
const s = Math.floor(secs % 60)
return `${m}:${s.toString().padStart(2, '0')}`
}
/**
* The DJ-style "prep strip" across the top of the window: transport controls on
* the left, waveforms on the right (a scrolling zoomable main view above a
* whole-track overview). Playback is driven by a single hidden <audio> element
* streamed from the backend (range-enabled, so seeking works). The frequency-
* coloured waveform is analysed once here and shared by both views.
*/
export function PrepStrip({ track, onError }: Props) {
const audioRef = useRef<HTMLAudioElement | null>(null)
const [playing, setPlaying] = useState(false)
const [current, setCurrent] = useState(0)
const [duration, setDuration] = useState(0)
const [loadError, setLoadError] = useState(false)
const [cols, setCols] = useState<WaveColumn[] | null>(null)
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const trackId = track?.id ?? null
// When the loaded track changes, reset transport state. The <audio> src is
// bound declaratively below, so changing trackId swaps the source.
useEffect(() => {
setPlaying(false)
setCurrent(0)
setDuration(0)
setLoadError(false)
}, [trackId])
// Analyse the waveform once per track; both waveform views share the result.
useEffect(() => {
if (!trackId) {
setCols(null)
setWaveStatus('loading')
return
}
let cancelled = false
setCols(null)
setWaveStatus('loading')
analyzeWaveform(api.audioUrl(trackId))
.then((c) => {
if (cancelled) return
setCols(c)
setWaveStatus('ready')
})
.catch(() => {
if (!cancelled) setWaveStatus('error')
})
return () => {
cancelled = true
}
}, [trackId])
const toggle = () => {
const el = audioRef.current
if (!el || !track) return
if (el.paused) {
el.play().catch(() => {
setLoadError(true)
setPlaying(false)
})
} else {
el.pause()
}
}
// Smoothly advance the playhead/time while playing (timeupdate is only ~4Hz).
useEffect(() => {
if (!playing) return
let raf = 0
const tick = () => {
const el = audioRef.current
if (el) setCurrent(el.currentTime)
raf = requestAnimationFrame(tick)
}
raf = requestAnimationFrame(tick)
return () => cancelAnimationFrame(raf)
}, [playing])
const seek = (t: number) => {
const el = audioRef.current
if (!el) return
el.currentTime = t
setCurrent(t)
}
const showWaves = track && !loadError && cols && waveStatus === 'ready'
return (
<div className="flex h-52 shrink-0 items-stretch gap-px border-b border-line bg-ink-950">
{/* Controls */}
<div className="flex w-72 shrink-0 flex-col justify-between bg-ink-900 px-4 py-3">
<div className="min-w-0">
{track ? (
<>
<div className="truncate text-sm font-semibold text-text" title={track.title ?? ''}>
{track.title ?? 'Untitled'}
</div>
<div className="truncate text-xs text-muted" title={track.artist ?? ''}>
{track.artist ?? 'Unknown artist'}
</div>
</>
) : (
<div className="text-xs uppercase tracking-wider text-faint">No track loaded</div>
)}
</div>
<div className="flex items-center gap-3">
<button
onClick={toggle}
disabled={!track || loadError}
className="flex h-9 w-9 items-center justify-center rounded-full border border-line bg-ink-850 text-text hover:border-accent disabled:opacity-40 disabled:hover:border-line"
title={playing ? 'Pause' : 'Play'}
>
{playing ? '❚❚' : '▶'}
</button>
<div className="tabular-nums text-xs text-faint">
{fmt(current)} / {fmt(duration)}
</div>
</div>
</div>
{/* Waveforms: scrolling main view above a whole-track overview. */}
<div className="relative flex min-w-0 flex-1 flex-col bg-ink-900">
{!track ? (
<div className="flex flex-1 items-center justify-center text-xs text-faint">
Load a track to prep it
</div>
) : loadError ? (
<div className="flex flex-1 items-center justify-center text-xs text-pink">
Could not load audio — file may be missing or unsupported by the browser.
</div>
) : (
<>
<div className="relative min-h-0 flex-1">
{showWaves ? (
<MainWaveform
cols={cols}
currentTime={current}
duration={duration}
onSeek={seek}
/>
) : (
<div className="flex h-full items-center justify-center text-xs text-faint">
{waveStatus === 'error' ? 'Waveform unavailable' : 'Analysing waveform…'}
</div>
)}
</div>
<div className="h-10 shrink-0 border-t border-line">
{showWaves && (
<OverviewWaveform
cols={cols}
currentTime={current}
duration={duration}
onSeek={seek}
/>
)}
</div>
</>
)}
</div>
{track && (
<audio
ref={audioRef}
src={api.audioUrl(track.id)}
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
onEnded={() => setPlaying(false)}
onTimeUpdate={(e) => setCurrent(e.currentTarget.currentTime)}
onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}
onError={() => {
setLoadError(true)
onError?.('Could not load audio for this track')
}}
/>
)}
</div>
)
}