Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/audio player: implement a vaweform seek bar
Adorian Doran5043116214f5
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b4db1f2416..78020e7dba 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1187,6 +1187,7 @@"media": {"play": "Play (Space)","pause": "Pause (Space)",+ "seek": "Seek (Left/Right arrow keys)","back-10s": "Back 10s (Left arrow key)","forward-30s": "Forward 30s","previous-video": "Previous video: {{- title}}",diff --git a/apps/client/src/widgets/type_widgets/file/Audio.tsx b/apps/client/src/widgets/type_widgets/file/Audio.tsxindex 3f57d3df7b..07b8eb7da9 100644--- a/apps/client/src/widgets/type_widgets/file/Audio.tsx+++ b/apps/client/src/widgets/type_widgets/file/Audio.tsx@@ -6,7 +6,9 @@ import { t } from "../../../services/i18n";import { getUrlForDownload } from "../../../services/open";import Icon from "../../react/Icon";import NoItems from "../../react/NoItems";-import { MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SeekBar, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";+import { loadWaveform } from "./audio_waveform";+import { MediaSiblingButton, PlaybackSpeed, PlayModeButton, PlayPauseButton, SkipButton, useMediaPlayMode, useMediaSessionController, VolumeControl } from "./MediaPlayer";+import { WaveformSeekBar } from "./WaveformSeekBar";export default function AudioPreview({ note, noteContext, isVisible = true }: { note: FNote, noteContext?: NoteContext, isVisible?: boolean }) {const wrapperRef = useRef<HTMLDivElement>(null);@@ -36,6 +38,7 @@ export default function AudioPreview({ note, noteContext, isVisible = true }: {const syncPlaying = useCallback(() => setPlaying(!!audioRef.current && !audioRef.current.paused), []);const { mode: playMode, setMode: setPlayMode } = useMediaPlayMode(noteContext, audioRef);const siblingNavigation = useMediaSessionController(note, noteContext, "audio/", audioRef, isVisible, playMode);+ const waveformPeaks = useWaveformPeaks(note.noteId);if (error) {return <NoItems icon="bx bx-volume-mute" text={t("media.unsupported-format", { mime: note.mime.replace("/", "-") })} />;@@ -57,7 +60,7 @@ export default function AudioPreview({ note, noteContext, isVisible = true }: {<Icon icon="bx bx-music" className="audio-preview-icon" /></div><div className="media-preview-controls">- <SeekBar mediaRef={audioRef} />+ <WaveformSeekBar mediaRef={audioRef} peaks={waveformPeaks} /><div class="media-buttons-row"><div className="left">@@ -83,6 +86,26 @@ export default function AudioPreview({ note, noteContext, isVisible = true }: {);}+/** Decode the note's audio into a normalized waveform for the seek bar. Returns `null` while loading or when no+ * waveform is available (oversized/undecodable file); the seek bar then falls back to a plain track. The fetch+ * is aborted when the note changes so a slow decode for a previous note can't paint over the current one. */+function useWaveformPeaks(noteId: string): number[] | null {+ const [peaks, setPeaks] = useState<number[] | null>(null);++ useEffect(() => {+ setPeaks(null);+ const controller = new AbortController();+ loadWaveform(getUrlForDownload(`api/notes/${noteId}/open`), { signal: controller.signal })+ .then((waveform) => {+ if (!controller.signal.aborted) setPeaks(waveform?.peaks ?? null);+ })+ .catch(() => {});+ return () => controller.abort();+ }, [ noteId ]);++ return peaks;+}+function useKeyboardShortcuts(audioRef: MutableRef<HTMLAudioElement | null>, togglePlayback: () => void) {return useCallback((e: KeyboardEvent) => {const audio = audioRef.current;diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsxindex ae0d45e92a..e2270c9e96 100644--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx@@ -68,7 +68,7 @@ export function SeekBar({ mediaRef }: { mediaRef: RefObject<HTMLVideoElement | H);}-function formatTime(seconds: number): string {+export function formatTime(seconds: number): string {const mins = Math.floor(seconds / 60);const secs = Math.floor(seconds % 60);return `${mins}:${secs.toString().padStart(2, "0")}`;diff --git a/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.css b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.cssnew file mode 100644index 0000000000..a8fd76dee8--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.css@@ -0,0 +1,21 @@+.waveform-seekbar {+ /* Placeholder colors — tune to taste. Read by the canvas renderer via getComputedStyle. */+ --waveform-played-color: #4caf9d;+ --waveform-unplayed-color: #5a5a5a;+ --waveform-silence-color: #333333;++ .waveform-canvas {+ flex: 1;+ min-width: 0;+ height: 42px;+ display: block;+ cursor: pointer;+ touch-action: none;+ border-radius: 4px;+ }++ .waveform-canvas:focus-visible {+ outline: 2px solid var(--waveform-played-color);+ outline-offset: 2px;+ }+}diff --git a/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsxnew file mode 100644index 0000000000..a66bd2dace--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/WaveformSeekBar.tsx@@ -0,0 +1,212 @@+import "./WaveformSeekBar.css";++import { RefObject } from "preact";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++import { t } from "../../../services/i18n";+import { formatTime } from "./MediaPlayer";++/** Below this normalized amplitude a bucket is considered silence and painted with the silence color. */+const SILENCE_THRESHOLD = 0.06;+/** Bar + gap geometry, in CSS pixels. The renderer fits as many bars as the width allows. */+const BAR_WIDTH = 2;+const BAR_GAP = 2;+const MIN_BAR_HEIGHT = 2;+/** Flat amplitude shown before the waveform is analyzed; the bars morph up/down from this to the real values. */+const FLAT_LEVEL = 0.1;+/** Duration of the flat → analyzed morph, in milliseconds. */+const MORPH_DURATION = 1000;+/** Keyboard seek step, as a fraction of the total duration; Home/End jump to the ends. */+const KEYBOARD_STEP = 0.05;++/**+ * Waveform seek bar: shown from the very start. Until the amplitude envelope is decoded it renders a flat+ * placeholder band; when {@link peaks} arrives the bars animate from flat to their real heights. Scrubbing works+ * throughout (it only needs the media element's duration), by mouse, touch (Pointer Events), or keyboard.+ */+export function WaveformSeekBar({ mediaRef, peaks }: { mediaRef: RefObject<HTMLVideoElement | HTMLAudioElement>; peaks: number[] | null }) {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const [currentTime, setCurrentTime] = useState(0);+ const [duration, setDuration] = useState(0);+ const [size, setSize] = useState({ width: 0, height: 0 });+ const [morph, setMorph] = useState(0);++ // Mirror the media element's clock — same seeding pattern as SeekBar: read the element now in case its+ // metadata already loaded before this passive effect attached the listeners.+ useEffect(() => {+ const media = mediaRef.current;+ if (!media) return;++ const onTimeUpdate = () => setCurrentTime(media.currentTime);+ const onDurationChange = () => setDuration(media.duration);+ onTimeUpdate();+ onDurationChange();++ media.addEventListener("timeupdate", onTimeUpdate);+ media.addEventListener("durationchange", onDurationChange);+ return () => {+ media.removeEventListener("timeupdate", onTimeUpdate);+ media.removeEventListener("durationchange", onDurationChange);+ };+ }, [ mediaRef ]);++ // Track the canvas' CSS size so the draw effect can run at device-pixel resolution.+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const observer = new ResizeObserver(() => setSize({ width: canvas.clientWidth, height: canvas.clientHeight }));+ observer.observe(canvas);+ setSize({ width: canvas.clientWidth, height: canvas.clientHeight });+ return () => observer.disconnect();+ }, []);++ // Animate flat → analyzed once the peaks are available. While they are null (loading or undecodable) morph+ // stays at 0 and the bars hold the flat placeholder.+ useEffect(() => {+ if (!peaks || peaks.length === 0) {+ setMorph(0);+ return;+ }+ let raf = 0;+ let startTs = 0;+ const tick = (ts: number) => {+ if (startTs === 0) startTs = ts;+ const linear = Math.min(1, (ts - startTs) / MORPH_DURATION);+ setMorph(1 - Math.pow(1 - linear, 3)); // ease-out cubic+ if (linear < 1) raf = requestAnimationFrame(tick);+ };+ raf = requestAnimationFrame(tick);+ return () => cancelAnimationFrame(raf);+ }, [ peaks ]);++ const progress = duration > 0 ? Math.min(1, currentTime / duration) : 0;++ useEffect(() => {+ drawWaveform(canvasRef.current, peaks, progress, size, morph);+ }, [ peaks, progress, size, morph ]);++ const seekToFraction = useCallback((fraction: number) => {+ const media = mediaRef.current;+ if (!media || !media.duration) return;+ media.currentTime = Math.max(0, Math.min(1, fraction)) * media.duration;+ }, [ mediaRef ]);++ const seekToClientX = useCallback((clientX: number) => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const rect = canvas.getBoundingClientRect();+ if (rect.width <= 0) return;+ seekToFraction((clientX - rect.left) / rect.width);+ }, [ seekToFraction ]);++ // Pointer Events unify mouse and touch. Capturing the pointer keeps scrubbing live even when the finger or+ // cursor strays outside the canvas mid-drag.+ const onPointerDown = useCallback((e: PointerEvent) => {+ e.preventDefault();+ canvasRef.current?.setPointerCapture(e.pointerId);+ seekToClientX(e.clientX);+ }, [ seekToClientX ]);++ const onPointerMove = useCallback((e: PointerEvent) => {+ const canvas = canvasRef.current;+ if (!canvas?.hasPointerCapture(e.pointerId)) return;+ seekToClientX(e.clientX);+ }, [ seekToClientX ]);++ const onKeyDown = useCallback((e: KeyboardEvent) => {+ switch (e.key) {+ case "ArrowLeft":+ e.preventDefault();+ seekToFraction(progress - KEYBOARD_STEP);+ break;+ case "ArrowRight":+ e.preventDefault();+ seekToFraction(progress + KEYBOARD_STEP);+ break;+ case "Home":+ e.preventDefault();+ seekToFraction(0);+ break;+ case "End":+ e.preventDefault();+ seekToFraction(1);+ break;+ }+ }, [ progress, seekToFraction ]);++ return (+ <div class="media-seekbar-row waveform-seekbar">+ <span class="media-time">{formatTime(currentTime)}</span>+ <canvas+ ref={canvasRef}+ class="waveform-canvas"+ role="slider"+ tabIndex={0}+ aria-label={t("media.seek")}+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(progress * 100)}+ aria-valuetext={`${formatTime(currentTime)} / ${formatTime(duration)}`}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onKeyDown={onKeyDown}+ />+ <span class="media-time">-{formatTime(Math.max(0, duration - currentTime))}</span>+ </div>+ );+}++function drawWaveform(canvas: HTMLCanvasElement | null, peaks: number[] | null, progress: number, size: { width: number; height: number }, morph: number) {+ if (!canvas || size.width <= 0 || size.height <= 0) return;+ const ctx = canvas.getContext("2d");+ if (!ctx) return;++ const dpr = window.devicePixelRatio || 1;+ const { width, height } = size;+ if (canvas.width !== Math.round(width * dpr) || canvas.height !== Math.round(height * dpr)) {+ canvas.width = Math.round(width * dpr);+ canvas.height = Math.round(height * dpr);+ }+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ ctx.clearRect(0, 0, width, height);++ const styles = getComputedStyle(canvas);+ const playedColor = resolveColor(styles, "--waveform-played-color", "#4caf9d");+ const unplayedColor = resolveColor(styles, "--waveform-unplayed-color", "#5a5a5a");+ const silenceColor = resolveColor(styles, "--waveform-silence-color", "#333333");++ const analyzed = !!peaks && peaks.length > 0;+ const barStride = BAR_WIDTH + BAR_GAP;+ const barCount = Math.max(1, Math.floor(width / barStride));+ const playX = progress * width;+ const mid = height / 2;+ const maxBarHeight = Math.max(MIN_BAR_HEIGHT, height - 2);++ for (let bar = 0; bar < barCount; bar++) {+ // Loudest sample in this bar's slice of the stored envelope, so brief peaks are not averaged away.+ let target = FLAT_LEVEL;+ if (analyzed && peaks) {+ target = 0;+ const start = Math.floor((bar / barCount) * peaks.length);+ const end = Math.max(start + 1, Math.floor(((bar + 1) / barCount) * peaks.length));+ for (let i = start; i < end && i < peaks.length; i++) {+ if (peaks[i] > target) target = peaks[i];+ }+ }++ // Morph from the flat placeholder to the analyzed height. Color is classified from the final target so+ // it stays stable during the animation rather than flickering as the height crosses the threshold.+ const amplitude = FLAT_LEVEL + (target - FLAT_LEVEL) * morph;+ const x = bar * barStride;+ const barHeight = Math.max(MIN_BAR_HEIGHT, amplitude * maxBarHeight);+ ctx.fillStyle = analyzed && target < SILENCE_THRESHOLD ? silenceColor : (x < playX ? playedColor : unplayedColor);+ ctx.fillRect(x, mid - barHeight / 2, BAR_WIDTH, barHeight);+ }+}++/** Read a CSS custom property, falling back to a literal default if the theme leaves it unset or the browser+ * hands back an unresolved `var(...)` reference. */+function resolveColor(styles: CSSStyleDeclaration, name: string, fallback: string): string {+ const value = styles.getPropertyValue(name).trim();+ return value && !value.startsWith("var(") ? value : fallback;+}diff --git a/apps/client/src/widgets/type_widgets/file/audio_waveform.spec.ts b/apps/client/src/widgets/type_widgets/file/audio_waveform.spec.tsnew file mode 100644index 0000000000..da98d131ae--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/audio_waveform.spec.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from "vitest";++import { computePeaks } from "./audio_waveform";++describe("computePeaks", () => {+ it("returns one normalized value per bucket", () => {+ const samples = new Float32Array([ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6 ]);+ const peaks = computePeaks(samples, 3);++ expect(peaks).toHaveLength(3);+ // Loudest bucket is normalized to exactly 1; every value stays within 0..1.+ expect(Math.max(...peaks)).toBeCloseTo(1);+ expect(peaks.every((p) => p >= 0 && p <= 1)).toBe(true);+ });++ it("ranks louder regions higher than quieter ones", () => {+ // First half quiet, second half loud.+ const samples = new Float32Array(1000);+ for (let i = 0; i < samples.length; i++) {+ samples[i] = i < 500 ? 0.05 : 0.9;+ }+ const peaks = computePeaks(samples, 2);++ expect(peaks[1]).toBeGreaterThan(peaks[0]);+ expect(peaks[1]).toBeCloseTo(1);+ });++ it("treats silence as zero", () => {+ const peaks = computePeaks(new Float32Array(100), 4);+ expect(peaks).toEqual([ 0, 0, 0, 0 ]);+ });++ it("is sign-independent (uses energy, not raw amplitude)", () => {+ const positive = computePeaks(new Float32Array([ 0.5, 0.5, 0.5, 0.5 ]), 2);+ const negative = computePeaks(new Float32Array([ -0.5, -0.5, -0.5, -0.5 ]), 2);+ expect(positive).toEqual(negative);+ });++ it("handles more buckets than samples without gaps", () => {+ const peaks = computePeaks(new Float32Array([ 1, 1 ]), 5);+ expect(peaks).toHaveLength(5);+ expect(peaks.every((p) => Number.isFinite(p))).toBe(true);+ });++ it("guards against empty input and non-positive bucket counts", () => {+ expect(computePeaks(new Float32Array(0), 3)).toEqual([ 0, 0, 0 ]);+ expect(computePeaks(new Float32Array([ 1, 2, 3 ]), 0)).toEqual([]);+ expect(computePeaks(new Float32Array([ 1, 2, 3 ]), -1)).toEqual([]);+ });+});diff --git a/apps/client/src/widgets/type_widgets/file/audio_waveform.ts b/apps/client/src/widgets/type_widgets/file/audio_waveform.tsnew file mode 100644index 0000000000..7fefdc0855--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/audio_waveform.ts@@ -0,0 +1,102 @@+/**+ * Waveform extraction for the audio seek bar.+ *+ * The seek bar renders the recording's amplitude envelope as vertical bars so the listener can see where+ * speech sits and where the silences are. We compute that envelope once per note by decoding the whole file+ * client-side — independent of the streaming `<audio>` element, so it is unaffected by range requests or any+ * cross-origin tainting of the media element.+ *+ * {@link computePeaks} is the pure, testable core; {@link loadWaveform} wraps it with the fetch + decode that+ * can only run in a browser with the Web Audio API.+ */++/** Resolution of the stored envelope. The renderer downsamples this to the available pixel width, so this is+ * just an upper bound on detail — high enough to stay crisp on a wide player, cheap enough to decode fast. */+export const WAVEFORM_BUCKETS = 1000;++/** Files larger than this are not decoded (decoding loads the whole thing into memory and is CPU-heavy);+ * the caller falls back to the plain seek bar. */+export const MAX_WAVEFORM_BYTES = 60 * 1024 * 1024;++export interface Waveform {+ /** Normalized 0..1 amplitude per bucket. */+ peaks: number[];+ /** Decoded duration in seconds. */+ duration: number;+}++/**+ * Reduce raw PCM samples to `buckets` normalized amplitudes using per-bucket RMS energy.+ *+ * RMS (rather than peak) is deliberate: it tracks perceived loudness, so sustained speech reads as tall bars+ * and silence/room-tone collapses to near-zero — which is exactly the "speech vs. silence" overview the seek+ * bar is for. The result is normalized so the loudest bucket is 1.+ *+ * Pure and synchronous so it can be unit-tested without the Web Audio API.+ */+export function computePeaks(samples: Float32Array, buckets: number): number[] {+ if (buckets <= 0) {+ return [];+ }+ if (samples.length === 0) {+ return new Array(buckets).fill(0);+ }++ const result = new Array<number>(buckets);+ const bucketSize = samples.length / buckets;+ let max = 0;++ for (let b = 0; b < buckets; b++) {+ const start = Math.floor(b * bucketSize);+ const end = Math.min(samples.length, Math.floor((b + 1) * bucketSize));+ let sumSquares = 0;+ let count = 0;+ for (let i = start; i < end; i++) {+ const s = samples[i];+ sumSquares += s * s;+ count++;+ }+ const rms = count > 0 ? Math.sqrt(sumSquares / count) : 0;+ result[b] = rms;+ if (rms > max) {+ max = rms;+ }+ }++ if (max > 0) {+ for (let b = 0; b < buckets; b++) {+ result[b] /= max;+ }+ }+ return result;+}++/**+ * Fetch the full audio file and decode it into a normalized waveform.+ *+ * Returns `null` (rather than throwing) for any condition the caller should treat as "no waveform, fall back+ * to the plain bar": oversized file, failed request, undecodable/unsupported format, or aborted navigation.+ */+export async function loadWaveform(url: string, { signal, buckets = WAVEFORM_BUCKETS }: { signal?: AbortSignal; buckets?: number } = {}): Promise<Waveform | null> {+ try {+ const response = await fetch(url, { signal, credentials: "include" });+ if (!response.ok) {+ return null;+ }++ const buffer = await response.arrayBuffer();+ if (buffer.byteLength === 0 || buffer.byteLength > MAX_WAVEFORM_BYTES) {+ return null;+ }++ // A 1-frame OfflineAudioContext is only used as a decoder here; its own sample rate is irrelevant to+ // decodeAudioData, which decodes at the file's native rate.+ const decoder = new OfflineAudioContext(1, 1, 44100);+ const audioBuffer = await decoder.decodeAudioData(buffer);+ const peaks = computePeaks(audioBuffer.getChannelData(0), buckets);+ return { peaks, duration: audioBuffer.duration };+ } catch {+ // Aborted fetch, network error, or decode failure — all mean "no waveform".+ return null;+ }+}