Open History to see the last commit
1import { useState } from "react";
2
3export function AudioPreview(props: {
4 readonly src: string;
5 readonly name: string;
6 /** Re-signed URLs with the same revision keep the loaded audio and its position. */
7 readonly revision?: string | null;
8 readonly onError?: () => void;
9}) {
10 const [loadedSource, setLoadedSource] = useState<{ src: string; revision: string } | null>(null);
11 const [playing, setPlaying] = useState(false);
12 const revision = props.revision ?? null;
13 // Changed files load once playback pauses.
14 if (loadedSource !== null && loadedSource.revision !== revision && !playing) {
15 setLoadedSource(revision === null ? null : { src: props.src, revision });
16 }
17 const src = loadedSource?.src ?? props.src;
18 return (
19 <div className="flex min-h-0 flex-1 items-center justify-center p-6">
20 <audio
21 controls
22 preload="metadata"
23 src={src}
24 aria-label={props.name}
25 className="w-full max-w-xl"
26 onLoadedMetadata={() => {
27 if (revision !== null && loadedSource === null) setLoadedSource({ src, revision });
28 }}
29 onPlay={() => setPlaying(true)}
30 onPause={() => setPlaying(false)}
31 onEnded={() => setPlaying(false)}
32 onError={() => {
33 setPlaying(false);
34 setLoadedSource(null);
35 if (src === props.src) props.onError?.();
36 }}
37 />
38 </div>
39 );
40}