A audio-player component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import {
4 ComponentProps,
5 createContext,
6 HTMLProps,
7 ReactNode,
8 RefObject,
9 useCallback,
10 useContext,
11 useEffect,
12 useMemo,
13 useRef,
14 useState,
15} from "react"
16import * as SliderPrimitive from "@radix-ui/react-slider"
17import { Check, PauseIcon, PlayIcon, Settings } from "lucide-react"
18
19import { cn } from "@/lib/utils"
20import { Button } from "@/components/ui/button"
21import {
22 DropdownMenu,
23 DropdownMenuContent,
24 DropdownMenuItem,
25 DropdownMenuTrigger,
26} from "@/components/ui/dropdown-menu"
27
28enum ReadyState {
29 HAVE_NOTHING = 0,
30 HAVE_METADATA = 1,
31 HAVE_CURRENT_DATA = 2,
32 HAVE_FUTURE_DATA = 3,
33 HAVE_ENOUGH_DATA = 4,
34}
35
36enum NetworkState {
37 NETWORK_EMPTY = 0,
38 NETWORK_IDLE = 1,
39 NETWORK_LOADING = 2,
40 NETWORK_NO_SOURCE = 3,
41}
42
43function formatTime(seconds: number) {
44 const hrs = Math.floor(seconds / 3600)
45 const mins = Math.floor((seconds % 3600) / 60)
46 const secs = Math.floor(seconds % 60)
47
48 const formattedMins = mins < 10 ? `0${mins}` : mins
49 const formattedSecs = secs < 10 ? `0${secs}` : secs
50
51 return hrs > 0
52 ? `${hrs}:${formattedMins}:${formattedSecs}`
53 : `${mins}:${formattedSecs}`
54}
55
56interface AudioPlayerItem<TData = unknown> {
57 id: string | number
58 src: string
59 data?: TData
60}
61
62interface AudioPlayerApi<TData = unknown> {
63 ref: RefObject<HTMLAudioElement | null>
64 activeItem: AudioPlayerItem<TData> | null
65 duration: number | undefined
66 error: MediaError | null
67 isPlaying: boolean
68 isBuffering: boolean
69 playbackRate: number
70 isItemActive: (id: string | number | null) => boolean
71 setActiveItem: (item: AudioPlayerItem<TData> | null) => Promise<void>
72 play: (item?: AudioPlayerItem<TData> | null) => Promise<void>
73 pause: () => void
74 seek: (time: number) => void
75 setPlaybackRate: (rate: number) => void
76}
77
78const AudioPlayerContext = createContext<AudioPlayerApi<unknown> | null>(null)
79
80export function useAudioPlayer<TData = unknown>(): AudioPlayerApi<TData> {
81 const api = useContext(AudioPlayerContext) as AudioPlayerApi<TData> | null
82 if (!api) {
83 throw new Error(
84 "useAudioPlayer cannot be called outside of AudioPlayerProvider"
85 )
86 }
87 return api
88}
89
90const AudioPlayerTimeContext = createContext<number | null>(null)
91
92export const useAudioPlayerTime = () => {
93 const time = useContext(AudioPlayerTimeContext)
94 if (time === null) {
95 throw new Error(
96 "useAudioPlayerTime cannot be called outside of AudioPlayerProvider"
97 )
98 }
99 return time
100}
101
102export function AudioPlayerProvider<TData = unknown>({
103 children,
104}: {
105 children: ReactNode
106}) {
107 const audioRef = useRef<HTMLAudioElement>(null)
108 const itemRef = useRef<AudioPlayerItem<TData> | null>(null)
109 const playPromiseRef = useRef<Promise<void> | null>(null)
110 const [readyState, setReadyState] = useState<number>(0)
111 const [networkState, setNetworkState] = useState<number>(0)
112 const [time, setTime] = useState<number>(0)
113 const [duration, setDuration] = useState<number | undefined>(undefined)
114 const [error, setError] = useState<MediaError | null>(null)
115 const [activeItem, _setActiveItem] = useState<AudioPlayerItem<TData> | null>(
116 null
117 )
118 const [paused, setPaused] = useState(true)
119 const [playbackRate, setPlaybackRateState] = useState<number>(1)
120
121 const setActiveItem = useCallback(
122 async (item: AudioPlayerItem<TData> | null) => {
123 if (!audioRef.current) return
124
125 if (item?.id === itemRef.current?.id) {
126 return
127 }
128 itemRef.current = item
129 const currentRate = audioRef.current.playbackRate
130 audioRef.current.pause()
131 audioRef.current.currentTime = 0
132 if (item === null) {
133 audioRef.current.removeAttribute("src")
134 } else {
135 audioRef.current.src = item.src
136 }
137 audioRef.current.load()
138 audioRef.current.playbackRate = currentRate
139 },
140 []
141 )
142
143 const play = useCallback(
144 async (item?: AudioPlayerItem<TData> | null) => {
145 if (!audioRef.current) return
146
147 if (playPromiseRef.current) {
148 try {
149 await playPromiseRef.current
150 } catch (error) {
151 console.error("Play promise error:", error)
152 }
153 }
154
155 if (item === undefined) {
156 const playPromise = audioRef.current.play()
157 playPromiseRef.current = playPromise
158 return playPromise
159 }
160 if (item?.id === activeItem?.id) {
161 const playPromise = audioRef.current.play()
162 playPromiseRef.current = playPromise
163 return playPromise
164 }
165
166 itemRef.current = item
167 const currentRate = audioRef.current.playbackRate
168 if (!audioRef.current.paused) {
169 audioRef.current.pause()
170 }
171 audioRef.current.currentTime = 0
172 if (item === null) {
173 audioRef.current.removeAttribute("src")
174 } else {
175 audioRef.current.src = item.src
176 }
177 audioRef.current.load()
178 audioRef.current.playbackRate = currentRate
179 const playPromise = audioRef.current.play()
180 playPromiseRef.current = playPromise
181 return playPromise
182 },
183 [activeItem]
184 )
185
186 const pause = useCallback(async () => {
187 if (!audioRef.current) return
188
189 if (playPromiseRef.current) {
190 try {
191 await playPromiseRef.current
192 } catch (e) {
193 console.error(e)
194 }
195 }
196
197 audioRef.current.pause()
198 playPromiseRef.current = null
199 }, [])
200
201 const seek = useCallback((time: number) => {
202 if (!audioRef.current) return
203 audioRef.current.currentTime = time
204 }, [])
205
206 const setPlaybackRate = useCallback((rate: number) => {
207 if (!audioRef.current) return
208 audioRef.current.playbackRate = rate
209 setPlaybackRateState(rate)
210 }, [])
211
212 const isItemActive = useCallback(
213 (id: string | number | null) => {
214 return activeItem?.id === id
215 },
216 [activeItem]
217 )
218
219 useAnimationFrame(() => {
220 if (audioRef.current) {
221 _setActiveItem(itemRef.current)
222 setReadyState(audioRef.current.readyState)
223 setNetworkState(audioRef.current.networkState)
224 setTime(audioRef.current.currentTime)
225 setDuration(audioRef.current.duration)
226 setPaused(audioRef.current.paused)
227 setError(audioRef.current.error)
228 setPlaybackRateState(audioRef.current.playbackRate)
229 }
230 })
231
232 const isPlaying = !paused
233 const isBuffering =
234 readyState < ReadyState.HAVE_FUTURE_DATA &&
235 networkState === NetworkState.NETWORK_LOADING
236
237 const api = useMemo<AudioPlayerApi<TData>>(
238 () => ({
239 ref: audioRef,
240 duration,
241 error,
242 isPlaying,
243 isBuffering,
244 activeItem,
245 playbackRate,
246 isItemActive,
247 setActiveItem,
248 play,
249 pause,
250 seek,
251 setPlaybackRate,
252 }),
253 [
254 audioRef,
255 duration,
256 error,
257 isPlaying,
258 isBuffering,
259 activeItem,
260 playbackRate,
261 isItemActive,
262 setActiveItem,
263 play,
264 pause,
265 seek,
266 setPlaybackRate,
267 ]
268 )
269
270 return (
271 <AudioPlayerContext.Provider value={api as AudioPlayerApi<unknown>}>
272 <AudioPlayerTimeContext.Provider value={time}>
273 <audio ref={audioRef} className="hidden" crossOrigin="anonymous" />
274 {children}
275 </AudioPlayerTimeContext.Provider>
276 </AudioPlayerContext.Provider>
277 )
278}
279
280export const AudioPlayerProgress = ({
281 ...otherProps
282}: Omit<
283 ComponentProps<typeof SliderPrimitive.Root>,
284 "min" | "max" | "value"
285>) => {
286 const player = useAudioPlayer()
287 const time = useAudioPlayerTime()
288 const wasPlayingRef = useRef(false)
289
290 return (
291 <SliderPrimitive.Root
292 {...otherProps}
293 value={[time]}
294 onValueChange={(vals) => {
295 player.seek(vals[0])
296 otherProps.onValueChange?.(vals)
297 }}
298 min={0}
299 max={player.duration ?? 0}
300 step={otherProps.step || 0.25}
301 onPointerDown={(e) => {
302 wasPlayingRef.current = player.isPlaying
303 player.pause()
304 otherProps.onPointerDown?.(e)
305 }}
306 onPointerUp={(e) => {
307 if (wasPlayingRef.current) {
308 player.play()
309 }
310 otherProps.onPointerUp?.(e)
311 }}
312 className={cn(
313 "group/player relative flex h-4 touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
314 otherProps.className
315 )}
316 onKeyDown={(e) => {
317 if (e.key === " ") {
318 e.preventDefault()
319 if (!player.isPlaying) {
320 player.play()
321 } else {
322 player.pause()
323 }
324 }
325 otherProps.onKeyDown?.(e)
326 }}
327 disabled={
328 player.duration === undefined ||
329 !Number.isFinite(player.duration) ||
330 Number.isNaN(player.duration)
331 }
332 >
333 <SliderPrimitive.Track className="bg-muted relative h-[4px] w-full grow overflow-hidden rounded-full">
334 <SliderPrimitive.Range className="bg-primary absolute h-full" />
335 </SliderPrimitive.Track>
336 <SliderPrimitive.Thumb
337 className="relative flex h-0 w-0 items-center justify-center opacity-0 group-hover/player:opacity-100 focus-visible:opacity-100 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
338 data-slot="slider-thumb"
339 >
340 <div className="bg-foreground absolute size-3 rounded-full" />
341 </SliderPrimitive.Thumb>
342 </SliderPrimitive.Root>
343 )
344}
345
346export const AudioPlayerTime = ({
347 className,
348 ...otherProps
349}: HTMLProps<HTMLSpanElement>) => {
350 const time = useAudioPlayerTime()
351 return (
352 <span
353 {...otherProps}
354 className={cn("text-muted-foreground text-sm tabular-nums", className)}
355 >
356 {formatTime(time)}
357 </span>
358 )
359}
360
361export const AudioPlayerDuration = ({
362 className,
363 ...otherProps
364}: HTMLProps<HTMLSpanElement>) => {
365 const player = useAudioPlayer()
366 return (
367 <span
368 {...otherProps}
369 className={cn("text-muted-foreground text-sm tabular-nums", className)}
370 >
371 {player.duration !== null &&
372 player.duration !== undefined &&
373 !Number.isNaN(player.duration)
374 ? formatTime(player.duration)
375 : "--:--"}
376 </span>
377 )
378}
379
380interface SpinnerProps {
381 className?: string
382}
383
384function Spinner({ className }: SpinnerProps) {
385 return (
386 <div
387 className={cn(
388 "border-muted border-t-foreground size-3.5 animate-spin rounded-full border-2",
389 className
390 )}
391 role="status"
392 aria-label="Loading"
393 >
394 <span className="sr-only">Loading...</span>
395 </div>
396 )
397}
398
399interface PlayButtonProps extends React.ComponentProps<typeof Button> {
400 playing: boolean
401 onPlayingChange: (playing: boolean) => void
402 loading?: boolean
403}
404
405const PlayButton = ({
406 playing,
407 onPlayingChange,
408 className,
409 onClick,
410 loading,
411 ...otherProps
412}: PlayButtonProps) => {
413 return (
414 <Button
415 {...otherProps}
416 onClick={(e) => {
417 onPlayingChange(!playing)
418 onClick?.(e)
419 }}
420 className={cn("relative", className)}
421 aria-label={playing ? "Pause" : "Play"}
422 type="button"
423 >
424 {playing ? (
425 <PauseIcon
426 className={cn("size-4", loading && "opacity-0")}
427 aria-hidden="true"
428 />
429 ) : (
430 <PlayIcon
431 className={cn("size-4", loading && "opacity-0")}
432 aria-hidden="true"
433 />
434 )}
435 {loading && (
436 <div className="absolute inset-0 flex items-center justify-center rounded-[inherit] backdrop-blur-xs">
437 <Spinner />
438 </div>
439 )}
440 </Button>
441 )
442}
443
444export interface AudioPlayerButtonProps<TData = unknown>
445 extends React.ComponentProps<typeof Button> {
446 item?: AudioPlayerItem<TData>
447}
448
449export function AudioPlayerButton<TData = unknown>({
450 item,
451 ...otherProps
452}: AudioPlayerButtonProps<TData>) {
453 const player = useAudioPlayer<TData>()
454
455 if (!item) {
456 return (
457 <PlayButton
458 {...otherProps}
459 playing={player.isPlaying}
460 onPlayingChange={(shouldPlay) => {
461 if (shouldPlay) {
462 player.play()
463 } else {
464 player.pause()
465 }
466 }}
467 loading={player.isBuffering && player.isPlaying}
468 />
469 )
470 }
471
472 return (
473 <PlayButton
474 {...otherProps}
475 playing={player.isItemActive(item.id) && player.isPlaying}
476 onPlayingChange={(shouldPlay) => {
477 if (shouldPlay) {
478 player.play(item)
479 } else {
480 player.pause()
481 }
482 }}
483 loading={
484 player.isItemActive(item.id) && player.isBuffering && player.isPlaying
485 }
486 />
487 )
488}
489
490type Callback = (delta: number) => void
491
492function useAnimationFrame(callback: Callback) {
493 const requestRef = useRef<number | null>(null)
494 const previousTimeRef = useRef<number | null>(null)
495 const callbackRef = useRef<Callback>(callback)
496
497 useEffect(() => {
498 callbackRef.current = callback
499 }, [callback])
500
501 useEffect(() => {
502 const animate = (time: number) => {
503 if (previousTimeRef.current !== null) {
504 const delta = time - previousTimeRef.current
505 callbackRef.current(delta)
506 }
507 previousTimeRef.current = time
508 requestRef.current = requestAnimationFrame(animate)
509 }
510
511 requestRef.current = requestAnimationFrame(animate)
512
513 return () => {
514 if (requestRef.current) cancelAnimationFrame(requestRef.current)
515 previousTimeRef.current = null
516 }
517 }, [])
518}
519
520const PLAYBACK_SPEEDS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2] as const
521
522export interface AudioPlayerSpeedProps
523 extends React.ComponentProps<typeof Button> {
524 speeds?: readonly number[]
525}
526
527export function AudioPlayerSpeed({
528 speeds = PLAYBACK_SPEEDS,
529 className,
530 variant = "ghost",
531 size = "icon",
532 ...props
533}: AudioPlayerSpeedProps) {
534 const player = useAudioPlayer()
535 const currentSpeed = player.playbackRate
536
537 return (
538 <DropdownMenu>
539 <DropdownMenuTrigger asChild>
540 <Button
541 variant={variant}
542 size={size}
543 className={cn(className)}
544 aria-label="Playback speed"
545 {...props}
546 >
547 <Settings className="size-4" />
548 </Button>
549 </DropdownMenuTrigger>
550 <DropdownMenuContent align="end" className="min-w-[120px]">
551 {speeds.map((speed) => (
552 <DropdownMenuItem
553 key={speed}
554 onClick={() => player.setPlaybackRate(speed)}
555 className="flex items-center justify-between"
556 >
557 <span className={speed === 1 ? "" : "font-mono"}>
558 {speed === 1 ? "Normal" : `${speed}x`}
559 </span>
560 {currentSpeed === speed && <Check className="size-4" />}
561 </DropdownMenuItem>
562 ))}
563 </DropdownMenuContent>
564 </DropdownMenu>
565 )
566}
567
568export interface AudioPlayerSpeedButtonGroupProps
569 extends Omit<React.HTMLAttributes<HTMLDivElement>, "children"> {
570 speeds?: readonly number[]
571}
572
573export function AudioPlayerSpeedButtonGroup({
574 speeds = [0.5, 1, 1.5, 2],
575 className,
576 ...props
577}: AudioPlayerSpeedButtonGroupProps) {
578 const player = useAudioPlayer()
579 const currentSpeed = player.playbackRate
580
581 return (
582 <div
583 className={cn("flex items-center gap-1", className)}
584 role="group"
585 aria-label="Playback speed controls"
586 {...props}
587 >
588 {speeds.map((speed) => (
589 <Button
590 key={speed}
591 variant={currentSpeed === speed ? "default" : "outline"}
592 size="sm"
593 onClick={() => player.setPlaybackRate(speed)}
594 className="min-w-[50px] font-mono text-xs"
595 >
596 {speed}x
597 </Button>
598 ))}
599 </div>
600 )
601}
602
603export const exampleTracks = [
604 {
605 id: "0",
606 name: "II - 00",
607 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/00.mp3",
608 },
609 {
610 id: "1",
611 name: "II - 01",
612 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/01.mp3",
613 },
614 {
615 id: "2",
616 name: "II - 02",
617 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/02.mp3",
618 },
619 {
620 id: "3",
621 name: "II - 03",
622 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/03.mp3",
623 },
624 {
625 id: "4",
626 name: "II - 04",
627 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/04.mp3",
628 },
629 {
630 id: "5",
631 name: "II - 05",
632 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/05.mp3",
633 },
634 {
635 id: "6",
636 name: "II - 06",
637 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/06.mp3",
638 },
639 {
640 id: "7",
641 name: "II - 07",
642 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/07.mp3",
643 },
644 {
645 id: "8",
646 name: "II - 08",
647 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/08.mp3",
648 },
649 {
650 id: "9",
651 name: "II - 09",
652 url: "https://storage.googleapis.com/eleven-public-cdn/audio/ui-elevenlabs-io/09.mp3",
653 },
654]
655