diff --git a/src/components/AudioPlayer/index.tsx b/src/components/AudioPlayer/index.tsx index eccbce2a..3a8dc54f 100644 --- a/src/components/AudioPlayer/index.tsx +++ b/src/components/AudioPlayer/index.tsx @@ -11,9 +11,11 @@ import logger from '@/lib/logger' interface AudioPlayerProps { src: string className?: string + /** Fires when enough data is buffered to play (e.g. to swap out a blurhash placeholder). */ + onReady?: () => void } -export default function AudioPlayer({ src, className }: AudioPlayerProps) { +export default function AudioPlayer({ src, className, onReady }: AudioPlayerProps) { const audioRef = useRef(null) const [isPlaying, setIsPlaying] = useState(false) const [currentTime, setCurrentTime] = useState(0) @@ -22,6 +24,25 @@ export default function AudioPlayer({ src, className }: AudioPlayerProps) { const seekTimeoutRef = useRef() const isSeeking = useRef(false) + useEffect(() => { + if (!onReady) return + const audio = audioRef.current + if (!audio) return + const notify = () => onReady() + if (audio.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) { + notify() + return + } + audio.addEventListener('canplay', notify, { once: true }) + return () => audio.removeEventListener('canplay', notify) + }, [src, onReady]) + + useEffect(() => { + if (error) { + onReady?.() + } + }, [error, onReady]) + useEffect(() => { const audio = audioRef.current if (!audio) return @@ -104,7 +125,7 @@ export default function AudioPlayer({ src, className }: AudioPlayerProps) { )} onClick={(e) => e.stopPropagation()} > -