Added waveform with controls

This commit is contained in:
Ben committed 2026-07-04 16:37:59 +02:00
1 parent fa7375d0e9
commit 5454784cff
5 files changed
+329 -24

No files matched your search

+69 -18
View File
@@ -6,8 +6,13 @@ interface Props {
currentTime: number currentTime: number
duration: number duration: number
onSeek: (t: number) => void onSeek: (t: number) => void
onScratchStart: () => void
onScratchMove: (t: number) => void
onScratchEnd: (t: number) => void
} }
const DRAG_THRESHOLD = 3 // px before a press becomes a scratch (vs a click-seek)
const MIN_SEC = 2 // most zoomed-in (seconds across the view) const MIN_SEC = 2 // most zoomed-in (seconds across the view)
const MAX_SEC = 64 // most zoomed-out const MAX_SEC = 64 // most zoomed-out
const DEFAULT_SEC = 16 const DEFAULT_SEC = 16
@@ -18,10 +23,24 @@ const DEFAULT_SEC = 16
* the zoom buttons change that window width. Repaints every frame (driven by the * the zoom buttons change that window width. Repaints every frame (driven by the
* parent's rAF-updated currentTime). * parent's rAF-updated currentTime).
*/ */
export function MainWaveform({ cols, currentTime, duration, onSeek }: Props) { export function MainWaveform({
cols,
currentTime,
duration,
onSeek,
onScratchStart,
onScratchMove,
onScratchEnd,
}: Props) {
const wrapRef = useRef<HTMLDivElement>(null) const wrapRef = useRef<HTMLDivElement>(null)
const canvasRef = useRef<HTMLCanvasElement>(null) const canvasRef = useRef<HTMLCanvasElement>(null)
const [secPerView, setSecPerView] = useState(DEFAULT_SEC) const [secPerView, setSecPerView] = useState(DEFAULT_SEC)
// Drag state for scratching. startTime is the playhead position at press;
// dragging maps horizontal movement to a time offset (right = earlier, so the
// waveform follows the cursor like grabbing a record).
const dragRef = useRef<{ startX: number; startTime: number; lastT: number; moved: boolean } | null>(
null,
)
// Draw closes over the latest props/state; a ref lets the ResizeObserver call // Draw closes over the latest props/state; a ref lets the ResizeObserver call
// the current version without re-subscribing. // the current version without re-subscribing.
@@ -45,9 +64,9 @@ export function MainWaveform({ cols, currentTime, duration, onSeek }: Props) {
} }
// Fixed centre playhead. // Fixed centre playhead.
const cx = Math.floor(w / 2) const pw = Math.max(2, Math.round(2 * dpr))
ctx.fillStyle = '#e6e9ef' ctx.fillStyle = '#e6e9ef'
ctx.fillRect(cx, 0, Math.max(1, Math.round(dpr)), h) ctx.fillRect(Math.floor(w / 2) - Math.floor(pw / 2), 0, pw, h)
} }
const drawRef = useRef(draw) const drawRef = useRef(draw)
@@ -66,29 +85,63 @@ export function MainWaveform({ cols, currentTime, duration, onSeek }: Props) {
return () => ro.disconnect() return () => ro.disconnect()
}, []) }, [])
// Click to seek: map horizontal offset from centre to a time delta. // A press that doesn't move is a seek (map offset from centre to a time);
const seek = (e: React.MouseEvent<HTMLDivElement>) => { // a press that moves is a scratch (map movement to a target time).
const timeAtClientX = (clientX: number, rect: DOMRect) => {
const ratioFromCenter = (clientX - rect.left) / rect.width - 0.5
return Math.min(duration, Math.max(0, currentTime + ratioFromCenter * secPerView))
}
const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
if (!duration) return if (!duration) return
e.currentTarget.setPointerCapture(e.pointerId)
dragRef.current = { startX: e.clientX, startTime: currentTime, lastT: currentTime, moved: false }
}
const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const d = dragRef.current
if (!d) return
const rect = e.currentTarget.getBoundingClientRect() const rect = e.currentTarget.getBoundingClientRect()
const ratioFromCenter = (e.clientX - rect.left) / rect.width - 0.5 const dx = e.clientX - d.startX
const t = currentTime + ratioFromCenter * secPerView if (!d.moved && Math.abs(dx) > DRAG_THRESHOLD) {
onSeek(Math.min(duration, Math.max(0, t))) d.moved = true
onScratchStart()
}
if (d.moved) {
const t = Math.min(duration, Math.max(0, d.startTime - (dx / rect.width) * secPerView))
d.lastT = t
onScratchMove(t)
}
}
const onPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
const d = dragRef.current
dragRef.current = null
if (!d) return
e.currentTarget.releasePointerCapture?.(e.pointerId)
if (d.moved) onScratchEnd(d.lastT)
else onSeek(timeAtClientX(e.clientX, e.currentTarget.getBoundingClientRect()))
} }
const zoomIn = () => setSecPerView((s) => Math.max(MIN_SEC, s / 2)) const zoomIn = () => setSecPerView((s) => Math.max(MIN_SEC, s / 2))
const zoomOut = () => setSecPerView((s) => Math.min(MAX_SEC, s * 2)) const zoomOut = () => setSecPerView((s) => Math.min(MAX_SEC, s * 2))
return ( return (
<div ref={wrapRef} onClick={seek} className="relative h-full w-full cursor-pointer"> <div
ref={wrapRef}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerUp}
className="relative h-full w-full cursor-ew-resize select-none touch-none"
>
<canvas ref={canvasRef} className="block h-full w-full" /> <canvas ref={canvasRef} className="block h-full w-full" />
{/* Zoom controls (Traktor-style +/-) */} {/* Zoom controls (Traktor-style +/-). stopPropagation on down so tapping a
button doesn't begin a scratch drag. */}
<div className="absolute right-2 top-2 flex flex-col gap-1"> <div className="absolute right-2 top-2 flex flex-col gap-1">
<button <button
onClick={(e) => { onPointerDown={(e) => e.stopPropagation()}
e.stopPropagation() onClick={zoomIn}
zoomIn()
}}
disabled={secPerView <= MIN_SEC} 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" 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" title="Zoom in"
@@ -96,10 +149,8 @@ export function MainWaveform({ cols, currentTime, duration, onSeek }: Props) {
+ +
</button> </button>
<button <button
onClick={(e) => { onPointerDown={(e) => e.stopPropagation()}
e.stopPropagation() onClick={zoomOut}
zoomOut()
}}
disabled={secPerView >= MAX_SEC} 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" 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" title="Zoom out"
+2 -1
View File
@@ -49,8 +49,9 @@ export function OverviewWaveform({ cols, currentTime, duration, onSeek }: Props)
const px = Math.round((timeRef.current / dur) * w) const px = Math.round((timeRef.current / dur) * w)
ctx.fillStyle = 'rgba(10,11,15,0.55)' ctx.fillStyle = 'rgba(10,11,15,0.55)'
ctx.fillRect(0, 0, px, h) ctx.fillRect(0, 0, px, h)
const pw = Math.max(2, Math.round(2 * (window.devicePixelRatio || 1)))
ctx.fillStyle = '#e6e9ef' ctx.fillStyle = '#e6e9ef'
ctx.fillRect(px, 0, 1, h) ctx.fillRect(px - Math.floor(pw / 2), 0, pw, h)
} }
}, []) }, [])
+92 -3
View File
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { api, type Track } from '../api' import { api, type Track } from '../api'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine'
import { MainWaveform } from './MainWaveform' import { MainWaveform } from './MainWaveform'
import { OverviewWaveform } from './OverviewWaveform' import { OverviewWaveform } from './OverviewWaveform'
@@ -33,6 +34,13 @@ export function PrepStrip({ track, onError }: Props) {
const [cols, setCols] = useState<WaveColumn[] | null>(null) const [cols, setCols] = useState<WaveColumn[] | null>(null)
const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading') const [waveStatus, setWaveStatus] = useState<'loading' | 'ready' | 'error'>('loading')
// Scratch engine (Web Audio) — holds the decoded buffer for the loaded track.
const audioCtxRef = useRef<AudioContext | null>(null)
const engineRef = useRef<ScratchEngine | null>(null)
const wasPlayingRef = useRef(false)
const scratchRafRef = useRef(0)
const engagedRef = useRef(false) // engine is dragging or coasting
const trackId = track?.id ?? null const trackId = track?.id ?? null
// When the loaded track changes, reset transport state. The <audio> src is // When the loaded track changes, reset transport state. The <audio> src is
@@ -44,8 +52,10 @@ export function PrepStrip({ track, onError }: Props) {
setLoadError(false) setLoadError(false)
}, [trackId]) }, [trackId])
// Analyse the waveform once per track; both waveform views share the result. // Analyse the waveform once per track; both waveform views share the result,
// and the decoded buffer is handed to the scratch engine (no second decode).
useEffect(() => { useEffect(() => {
engineRef.current = null
if (!trackId) { if (!trackId) {
setCols(null) setCols(null)
setWaveStatus('loading') setWaveStatus('loading')
@@ -55,10 +65,13 @@ export function PrepStrip({ track, onError }: Props) {
setCols(null) setCols(null)
setWaveStatus('loading') setWaveStatus('loading')
analyzeWaveform(api.audioUrl(trackId)) analyzeWaveform(api.audioUrl(trackId))
.then((c) => { .then((res) => {
if (cancelled) return if (cancelled) return
setCols(c) setCols(res.cols)
setWaveStatus('ready') setWaveStatus('ready')
const eng = new ScratchEngine()
eng.load(res.buffer)
engineRef.current = eng
}) })
.catch(() => { .catch(() => {
if (!cancelled) setWaveStatus('error') if (!cancelled) setWaveStatus('error')
@@ -101,6 +114,79 @@ export function PrepStrip({ track, onError }: Props) {
setCurrent(t) setCurrent(t)
} }
// ---- scratch (Web Audio) ----------------------------------------------
const getCtx = (): AudioContext => {
if (!audioCtxRef.current) {
audioCtxRef.current = new (window.AudioContext ??
(window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext)()
}
void audioCtxRef.current.resume()
return audioCtxRef.current
}
// Once the platter has coasted to a stop (or up to normal speed), hand the
// position back to the <audio> element and resume if it had been playing.
const finalizeScratch = () => {
cancelAnimationFrame(scratchRafRef.current)
engagedRef.current = false
const eng = engineRef.current
if (!eng) return
const finalSec = eng.end()
const el = audioRef.current
if (el) el.currentTime = finalSec
setCurrent(finalSec)
if (wasPlayingRef.current && el) void el.play().catch(() => {})
}
// Follow the engine's actual position each frame; finalize when it settles.
const runScratchRaf = () => {
cancelAnimationFrame(scratchRafRef.current)
const eng = engineRef.current!
const tick = () => {
setCurrent(eng.getPositionSec())
if (eng.finished) {
finalizeScratch()
return
}
scratchRafRef.current = requestAnimationFrame(tick)
}
scratchRafRef.current = requestAnimationFrame(tick)
}
const onScratchStart = () => {
const eng = engineRef.current
// Re-grab while still coasting: keep the current position, resume dragging.
if (engagedRef.current && eng) {
eng.regrab()
return
}
const el = audioRef.current
wasPlayingRef.current = !!el && !el.paused
if (el && !el.paused) el.pause()
if (eng && eng.loaded) {
eng.begin(getCtx(), current)
engagedRef.current = true
runScratchRaf()
}
}
const onScratchMove = (t: number) => {
if (engagedRef.current) engineRef.current!.setTargetSec(t)
else setCurrent(t) // no decoded buffer yet → silent visual scrub
}
const onScratchEnd = (t: number) => {
if (engagedRef.current) {
// Coast; runScratchRaf finalizes once the platter settles.
engineRef.current!.release(wasPlayingRef.current)
} else {
const el = audioRef.current
if (el) el.currentTime = t
setCurrent(t)
if (wasPlayingRef.current && el) void el.play().catch(() => {})
}
}
const showWaves = track && !loadError && cols && waveStatus === 'ready' const showWaves = track && !loadError && cols && waveStatus === 'ready'
return ( return (
@@ -156,6 +242,9 @@ export function PrepStrip({ track, onError }: Props) {
currentTime={current} currentTime={current}
duration={duration} duration={duration}
onSeek={seek} onSeek={seek}
onScratchStart={onScratchStart}
onScratchMove={onScratchMove}
onScratchEnd={onScratchEnd}
/> />
) : ( ) : (
<div className="flex h-full items-center justify-center text-xs text-faint"> <div className="flex h-full items-center justify-center text-xs text-faint">
+158
View File
@@ -0,0 +1,158 @@
// A minimal "scratch" engine: while the user drags the waveform we play the
// decoded audio at a position that glides toward the cursor's target. Fast drags
// → high pitch, reverse drags → reverse audio, holding still → silence — the
// characteristic scratch behaviour, which a plain <audio> element can't do
// (no reverse, no arbitrary rate).
//
// On release the engine coasts: it keeps the drag velocity and eases it toward a
// target speed with friction (momentum/flywheel feel) — to a stop if playback was
// paused, or up to normal speed if it was playing. When it settles, `finished`
// flips true and the caller hands the position back to the <audio> element.
//
// Uses a ScriptProcessorNode: deprecated but universally supported and runs on
// the main thread, so `position`/`finished` are directly readable for visual
// sync. Moving to an AudioWorklet is the natural hardening step later.
const BUFFER_SIZE = 512
const GLIDE = 400 // samples: how tightly position chases the target while dragging
const RATE_CAP = 12 // max samples advanced per output sample (pitch ceiling)
const INERTIA_FRICTION = 0.9998 // per-sample easing toward the target velocity (~0.4s spin-down)
const SETTLE_EPS = 0.02 // |velocity - target| below this → settled
type Mode = 'drag' | 'inertia' | 'done'
export class ScratchEngine {
private channels: Float32Array[] = []
private length = 0
private sr = 44100
private ctxRate = 44100
private node: ScriptProcessorNode | null = null
private position = 0 // in source samples
private target = 0 // drag target, in source samples
private velocity = 0 // source samples advanced per output sample
private targetVelocity = 0 // inertia goal
private mode: Mode = 'drag'
load(buffer: AudioBuffer): void {
this.channels = []
for (let c = 0; c < buffer.numberOfChannels; c++) {
this.channels.push(buffer.getChannelData(c))
}
this.length = buffer.length
this.sr = buffer.sampleRate
}
get loaded(): boolean {
return this.length > 0
}
get finished(): boolean {
return this.mode === 'done'
}
getPositionSec(): number {
return this.position / this.sr
}
/** Enter scratch mode at the given position (creates the audio node if needed). */
begin(ctx: AudioContext, positionSec: number): void {
if (!this.loaded) return
this.ctxRate = ctx.sampleRate
this.position = positionSec * this.sr
this.target = this.position
this.velocity = 0
this.mode = 'drag'
if (!this.node) {
const node = ctx.createScriptProcessor(BUFFER_SIZE, 0, 2)
node.onaudioprocess = (e) => this.render(e)
node.connect(ctx.destination)
this.node = node
}
}
/** Re-grab while the platter is still coasting: resume dragging from here. */
regrab(): void {
this.mode = 'drag'
this.target = this.position
}
setTargetSec(sec: number): void {
this.target = Math.max(0, Math.min(this.length - 1, sec * this.sr))
}
/** Release the platter: coast with the current velocity, easing toward normal
* speed (resume=true) or a stop (resume=false). `finished` flips when settled. */
release(resume: boolean): void {
this.targetVelocity = resume ? this.sr / this.ctxRate : 0
this.mode = 'inertia'
}
/** Tear down the audio node; returns the final position (seconds). */
end(): number {
if (this.node) {
this.node.disconnect()
this.node.onaudioprocess = null
this.node = null
}
return this.position / this.sr
}
private sample(outs: Float32Array[], i: number, chN: number): void {
const i0 = Math.floor(this.position)
const frac = this.position - i0
for (let c = 0; c < chN; c++) {
const src = this.channels[Math.min(c, this.channels.length - 1)]
outs[c][i] = i0 + 1 < this.length ? src[i0] * (1 - frac) + src[i0 + 1] * frac : src[i0]
}
}
private silence(outs: Float32Array[], i: number, chN: number): void {
for (let c = 0; c < chN; c++) outs[c][i] = 0
}
private render(e: AudioProcessingEvent): void {
const out = e.outputBuffer
const n = out.length
const chN = out.numberOfChannels
const outs: Float32Array[] = []
for (let c = 0; c < chN; c++) outs.push(out.getChannelData(c))
for (let i = 0; i < n; i++) {
if (this.mode === 'drag') {
const diff = this.target - this.position
if (Math.abs(diff) < 1) {
// Hand at rest on the platter → no movement, no sound.
this.velocity = 0
this.silence(outs, i, chN)
continue
}
let step = diff / GLIDE
if (step > RATE_CAP) step = RATE_CAP
else if (step < -RATE_CAP) step = -RATE_CAP
this.position += step
this.velocity = this.velocity * 0.9 + step * 0.1 // smoothed, for release momentum
} else if (this.mode === 'inertia') {
this.velocity = this.targetVelocity + (this.velocity - this.targetVelocity) * INERTIA_FRICTION
this.position += this.velocity
if (Math.abs(this.velocity - this.targetVelocity) < SETTLE_EPS) {
this.mode = 'done'
}
} else {
this.silence(outs, i, chN)
continue
}
// Clamp to the track; hitting an edge kills momentum.
if (this.position < 0) {
this.position = 0
this.velocity = 0
if (this.mode === 'inertia') this.mode = 'done'
} else if (this.position > this.length - 1) {
this.position = this.length - 1
this.velocity = 0
if (this.mode === 'inertia') this.mode = 'done'
}
this.sample(outs, i, chN)
}
}
}
+8 -2
View File
@@ -68,7 +68,13 @@ export function paintWave(
} }
} }
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveColumn[]> { export interface WaveformAnalysis {
cols: WaveColumn[]
/** The decoded audio, retained for the scratch engine (reused, not re-decoded). */
buffer: AudioBuffer
}
export async function analyzeWaveform(url: string, buckets?: number): Promise<WaveformAnalysis> {
const resp = await fetch(url) const resp = await fetch(url)
if (!resp.ok) throw new Error(`audio fetch failed: ${resp.status}`) if (!resp.ok) throw new Error(`audio fetch failed: ${resp.status}`)
const arr = await resp.arrayBuffer() const arr = await resp.arrayBuffer()
@@ -168,5 +174,5 @@ export async function analyzeWaveform(url: string, buckets?: number): Promise<Wa
b: Math.pow(h / mx, 1.3), b: Math.pow(h / mx, 1.3),
} }
} }
return cols return { cols, buffer: audio }
} }