{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "audio-player",
  "type": "registry:ui",
  "title": "Audio Player",
  "description": "The parts of a sound player around an `<audio>` element: play, a waveform that is also the time bar, time, speed and mute.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/announce",
    "@rivier-ui/cn",
    "@rivier-ui/use-media"
  ],
  "files": [
    {
      "path": "registry/ui/audio-player.tsx",
      "type": "registry:ui",
      "target": "components/ui/audio-player.tsx",
      "content": "\"use client\";\n/**\n * @name audio-player\n * @category ui\n * @description The parts of a sound player around an `<audio>` element: play, a waveform that is also the time bar, time, speed and mute.\n * @when A voice note, a recording, a clip of music or narration a person plays and seeks in. The project gives the element its source and, for the waveform, the peaks (computed ahead of time, or with computePeaks for a short clip); without peaks the bar is a flat line of the same size. Offer a Transcript (from captions) for anything spoken. Nothing plays by itself. For video use video-player; for a plain time bar without a waveform use scrubber.\n * @example\n * <AudioPlayer aria-label=\"Voice note from Ana\">\n *   <AudioPlayerAudio src=\"/note.mp3\" />\n *   <AudioPlayerPlay />\n *   <AudioPlayerWaveform peaks={peaks} />\n *   <AudioPlayerTime />\n *   <AudioPlayerRate />\n *   <AudioPlayerMute />\n * </AudioPlayer>\n *\n * // Peaks for a short clip, in the browser\n * const peaks = await computePeaks(await (await fetch(\"/note.mp3\")).arrayBuffer(), 64);\n */\nimport { Pause, Play, Volume2, VolumeX } from \"lucide-react\";\nimport { createContext, use, useImperativeHandle, useState, type ComponentProps, type KeyboardEvent, type PointerEvent } from \"react\";\nimport { announce } from \"@/lib/announce\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  MediaContext,\n  describeMediaTime,\n  formatMediaRate,\n  formatMediaTime,\n  isTypingTarget,\n  nextMediaRate,\n  useMediaContext,\n  useMediaProvider,\n  type MediaProviderOptions,\n} from \"@/lib/use-media\";\n\n/** Every word the player says. Pass `labels` to translate any of them. */\nexport type AudioPlayerLabels = { play: string; pause: string; mute: string; seek: string; rate: string; muted: string; unmuted: string; error: string };\n\nconst LABELS: AudioPlayerLabels = {\n  play: \"Play\",\n  pause: \"Pause\",\n  mute: \"Mute\",\n  seek: \"Seek\",\n  rate: \"Playback speed\",\n  muted: \"Muted\",\n  unmuted: \"Sound on\",\n  error: \"This sound could not be played.\",\n};\n\nconst LabelsContext = createContext<AudioPlayerLabels>(LABELS);\n\nexport type AudioPlayerProps = ComponentProps<\"div\"> &\n  MediaProviderOptions & {\n    /** Seconds Left and Right move by. Default 5. */\n    seekStep?: number;\n    labels?: Partial<AudioPlayerLabels>;\n  };\n\n/**\n * A named group laid out as one row that wraps. While focus is inside it, K plays and pauses, M mutes, and\n * Left and Right go back and forward (time runs left to right in every language, like the waveform). Name it\n * with `aria-label`: what the sound is.\n */\nexport function AudioPlayer({ className, seekStep = 5, labels, locale, captions, defaultCaptions, onCaptionsChange, children, onKeyDown, ...props }: AudioPlayerProps) {\n  const media = useMediaProvider({ locale, captions, defaultCaptions, onCaptionsChange });\n  const { state, actions } = media;\n  const words = { ...LABELS, ...labels };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || isTypingTarget(event.target)) return;\n    const onSlider = (event.target as HTMLElement).closest(\"[role=slider]\") !== null;\n    const key = event.key.length === 1 ? event.key.toLowerCase() : event.key;\n    const act: Record<string, (() => void) | undefined> = {\n      k: actions.toggle,\n      m: () => {\n        announce(state.muted ? words.unmuted : words.muted);\n        actions.toggleMuted();\n      },\n      ArrowLeft: onSlider ? undefined : () => actions.seekBy(-seekStep),\n      ArrowRight: onSlider ? undefined : () => actions.seekBy(seekStep),\n    };\n    const run = act[key];\n    if (!run) return;\n    event.preventDefault();\n    run();\n  };\n\n  return (\n    <MediaContext value={media}>\n      <LabelsContext value={words}>\n        <div\n          data-slot=\"audio-player\"\n          role=\"group\"\n          data-playing={state.playing ? \"\" : undefined}\n          className={cn(\"flex w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded-surface border bg-card p-2 text-card-foreground\", className)}\n          onKeyDown={handleKeyDown}\n          {...props}\n        >\n          {children}\n          {state.error !== null ? (\n            <p data-slot=\"audio-player-error\" role=\"alert\" className=\"w-full px-1 text-sm text-destructive\">\n              {words.error}\n            </p>\n          ) : null}\n        </div>\n      </LabelsContext>\n    </MediaContext>\n  );\n}\n\n/** The `<audio>` element: give it `src` or `<source>` children. It draws nothing (the parts are the controls) and never plays by itself. */\nexport function AudioPlayerAudio({ ref, children, ...props }: ComponentProps<\"audio\">) {\n  const { media, setMedia } = useMediaContext(\"AudioPlayerAudio\");\n  // The player holds the element; a ref from the project is given the same one.\n  useImperativeHandle(ref, () => media as HTMLAudioElement, [media]);\n  return (\n    <audio ref={setMedia} data-slot=\"audio-player-audio\" preload=\"metadata\" {...props}>\n      {children}\n    </audio>\n  );\n}\n\ntype ControlButtonProps = Omit<ComponentProps<\"button\">, \"type\">;\n\nconst controlButton =\n  \"inline-flex h-8 min-w-8 shrink-0 items-center justify-center gap-1 rounded-control px-1.5 text-sm font-medium text-foreground transition-[background-color,opacity] duration-instant ease-out select-none hover:bg-accent disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none pointer-coarse:h-(--control-h) pointer-coarse:min-w-(--control-h) [&_svg]:size-4 [&_svg]:shrink-0\";\n\n/** Plays or pauses, in the highlight colour: the one main action. Its name is what pressing it will do: \"Play\", then \"Pause\". */\nexport function AudioPlayerPlay({ className, children, onClick, ...props }: ControlButtonProps) {\n  const { state, actions } = useMediaContext(\"AudioPlayerPlay\");\n  const labels = use(LabelsContext);\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"audio-player-play\"\n      aria-label={state.playing ? labels.pause : labels.play}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) actions.toggle();\n      }}\n      className={cn(controlButton, \"size-(--control-h) bg-primary px-0 text-primary-foreground hover:bg-primary hover:opacity-90\", className)}\n      {...props}\n    >\n      {children ?? (state.playing ? <Pause aria-hidden=\"true\" strokeWidth={1.5} /> : <Play aria-hidden=\"true\" strokeWidth={1.5} />)}\n    </button>\n  );\n}\n\n/** Elapsed and total time, in figures of equal width. Not a live region: the waveform says the time when asked. */\nexport function AudioPlayerTime({ className, ...props }: ComponentProps<\"span\">) {\n  const { state, locale } = useMediaContext(\"AudioPlayerTime\");\n  return (\n    <span data-slot=\"audio-player-time\" className={cn(\"shrink-0 px-1 text-xs whitespace-nowrap text-muted-foreground tabular-nums\", className)} {...props}>\n      <span data-slot=\"audio-player-elapsed\" className=\"text-foreground\">\n        {formatMediaTime(state.time, locale)}\n      </span>\n      {\" / \"}\n      <span data-slot=\"audio-player-duration\">{formatMediaTime(state.duration, locale)}</span>\n    </span>\n  );\n}\n\n/** Mutes or unmutes: a toggle whose pressed state says whether it is on. */\nexport function AudioPlayerMute({ className, children, onClick, ...props }: ControlButtonProps) {\n  const { state, actions } = useMediaContext(\"AudioPlayerMute\");\n  const labels = use(LabelsContext);\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"audio-player-mute\"\n      aria-label={labels.mute}\n      aria-pressed={state.muted}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) actions.toggleMuted();\n      }}\n      className={cn(controlButton, className)}\n      {...props}\n    >\n      {children ?? (state.muted ? <VolumeX aria-hidden=\"true\" strokeWidth={1.5} /> : <Volume2 aria-hidden=\"true\" strokeWidth={1.5} />)}\n    </button>\n  );\n}\n\nconst RATES = [1, 1.25, 1.5, 2, 0.75] as const;\n\n/** The playback speed: each press goes to the next of `rates` and says it. Its name carries the speed (\"Playback speed: 1.5×\"). */\nexport function AudioPlayerRate({ className, rates = RATES, onClick, children, ...props }: ControlButtonProps & { rates?: readonly number[] }) {\n  const { state, actions, locale } = useMediaContext(\"AudioPlayerRate\");\n  const labels = use(LabelsContext);\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"audio-player-rate\"\n      aria-label={`${labels.rate}: ${formatMediaRate(state.rate, locale)}`}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented) return;\n        const next = nextMediaRate(rates, state.rate);\n        actions.setRate(next);\n        announce(`${labels.rate}: ${formatMediaRate(next, locale)}`);\n      }}\n      className={cn(controlButton, className)}\n      {...props}\n    >\n      {children ?? <span dir=\"ltr\" className=\"min-w-8 text-center text-xs tabular-nums\">{formatMediaRate(state.rate, locale)}</span>}\n    </button>\n  );\n}\n\nexport type AudioPlayerWaveformProps = Omit<ComponentProps<\"div\">, \"children\" | \"dir\"> & {\n  /** One number from 0 to 1 per bar: how loud that slice of the sound is. Left out (not computed yet), a flat line of the same size is drawn. */\n  peaks?: readonly number[] | undefined;\n  /** How many bars the flat line has while there are no peaks. Default 48. */\n  bars?: number;\n  /** Seconds Left and Right move by. Default 5. */\n  keyStep?: number;\n  /** Seconds Page Up and Page Down move by. Default 30. */\n  pageStep?: number;\n  /** \"ltr\" (default): time runs left to right in every language. \"rtl\" mirrors the drawing and the keys together. */\n  dir?: \"ltr\" | \"rtl\";\n  /** What a screen reader says for a position. Default: \"5 seconds of 20 seconds\". Replace it to translate \"of\". */\n  valueText?: (time: number, duration: number) => string;\n};\n\n/**\n * The sound drawn as bars, and the time bar at once: it is a slider (role=\"slider\"). What has played is in\n * the highlight colour with a line at the playing position, so the position does not rest on colour alone.\n * Press or drag to seek; Right and Left move by `keyStep`, Page Up and Page Down by `pageStep`, Home and End\n * go to the ends. It takes the width left in the row and keeps its height with or without peaks.\n */\nexport function AudioPlayerWaveform({\n  className,\n  peaks,\n  bars = 48,\n  keyStep = 5,\n  pageStep = 30,\n  dir = \"ltr\",\n  valueText,\n  onKeyDown,\n  onPointerDown,\n  onPointerMove,\n  onPointerUp,\n  onPointerCancel,\n  ...props\n}: AudioPlayerWaveformProps) {\n  const { state, actions, locale } = useMediaContext(\"AudioPlayerWaveform\");\n  const labels = use(LabelsContext);\n  const known = state.duration > 0;\n  const duration = known ? state.duration : 1;\n  /** Where it is being dragged to, until it is let go. */\n  const [drag, setDrag] = useState<number | null>(null);\n  const time = Math.min(duration, Math.max(0, drag ?? state.time));\n  const progress = time / duration;\n  const heights = peaks && peaks.length > 0 ? peaks : null;\n  const count = heights ? heights.length : bars;\n\n  const timeAt = (event: PointerEvent<HTMLDivElement>): number => {\n    const rect = event.currentTarget.getBoundingClientRect();\n    const fraction = rect.width > 0 ? Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width)) : 0;\n    return (dir === \"rtl\" ? 1 - fraction : fraction) * duration;\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || !known) return;\n    const forward = dir === \"rtl\" ? \"ArrowLeft\" : \"ArrowRight\";\n    const back = dir === \"rtl\" ? \"ArrowRight\" : \"ArrowLeft\";\n    const moves: Record<string, number | undefined> = {\n      [forward]: time + keyStep,\n      [back]: time - keyStep,\n      ArrowUp: time + keyStep,\n      ArrowDown: time - keyStep,\n      PageUp: time + pageStep,\n      PageDown: time - pageStep,\n      Home: 0,\n      End: duration,\n    };\n    const next = moves[event.key];\n    if (next === undefined) return;\n    event.preventDefault();\n    event.stopPropagation();\n    actions.seek(next);\n  };\n\n  return (\n    <div\n      data-slot=\"audio-player-waveform\"\n      role=\"slider\"\n      tabIndex={known ? 0 : -1}\n      dir={dir}\n      aria-label={labels.seek}\n      aria-orientation=\"horizontal\"\n      aria-valuemin={0}\n      aria-valuemax={Math.round(duration)}\n      aria-valuenow={Math.round(time)}\n      aria-valuetext={known ? (valueText ? valueText(time, duration) : `${describeMediaTime(time, locale)} of ${describeMediaTime(duration, locale)}`) : undefined}\n      aria-disabled={known ? undefined : true}\n      data-peaks={heights ? \"\" : undefined}\n      onKeyDown={handleKeyDown}\n      onPointerDown={(event) => {\n        onPointerDown?.(event);\n        if (event.defaultPrevented || event.button !== 0 || !known) return;\n        event.currentTarget.setPointerCapture(event.pointerId);\n        setDrag(timeAt(event));\n      }}\n      onPointerMove={(event) => {\n        onPointerMove?.(event);\n        if (drag !== null) setDrag(timeAt(event));\n      }}\n      onPointerUp={(event) => {\n        onPointerUp?.(event);\n        if (drag === null) return;\n        actions.seek(timeAt(event));\n        setDrag(null);\n      }}\n      onPointerCancel={(event) => {\n        onPointerCancel?.(event);\n        setDrag(null);\n      }}\n      className={cn(\"relative h-12 min-w-24 flex-1 cursor-pointer touch-pan-y rounded-control select-none aria-disabled:cursor-default aria-disabled:opacity-60\", className)}\n      {...props}\n    >\n      <svg aria-hidden=\"true\" viewBox={`0 0 ${count} 100`} preserveAspectRatio=\"none\" className={cn(\"size-full\", dir === \"rtl\" && \"-scale-x-100\")}>\n        {Array.from({ length: count }, (_, index) => {\n          // A flat line while there are no peaks; never less than a visible stub.\n          const height = heights ? Math.max(6, Math.min(1, heights[index] ?? 0) * 100) : 6;\n          const played = (index + 0.5) / count <= progress;\n          return <rect key={index} x={index + 0.2} y={(100 - height) / 2} width={0.6} height={height} className={played ? \"fill-primary\" : \"fill-muted-foreground opacity-60\"} />;\n        })}\n      </svg>\n      <span\n        aria-hidden=\"true\"\n        data-slot=\"audio-player-playhead\"\n        className=\"pointer-events-none absolute inset-y-0 w-0.5 -translate-x-1/2 bg-foreground rtl:translate-x-1/2\"\n        style={{ insetInlineStart: `${progress * 100}%` }}\n      />\n    </div>\n  );\n}\n\n/**\n * Peaks for AudioPlayerWaveform from a sound file's bytes: decodes it with Web Audio in the browser and\n * returns `count` numbers from 0 to 1 (the loudest sample of each slice, scaled so the loudest slice is 1).\n * It holds the whole decoded sound in memory, so it is meant for voice notes and clips of a few minutes\n * (files under about 10 MB); for anything longer compute the peaks once on the server and store them with\n * the file. Rejects when the browser cannot decode the file.\n */\nexport async function computePeaks(data: ArrayBuffer, count = 64): Promise<number[]> {\n  // An offline context decodes without a gesture and without opening a sound device.\n  const context = new OfflineAudioContext(1, 1, 44100);\n  const audio = await context.decodeAudioData(data.slice(0));\n  const samples = audio.getChannelData(0);\n  const size = Math.max(1, Math.floor(samples.length / count));\n  // Reading every sample of a long clip would block the page: look at up to about 500 samples per slice.\n  const stride = Math.max(1, Math.floor(size / 500));\n  const peaks: number[] = [];\n  for (let slice = 0; slice < count; slice += 1) {\n    let loudest = 0;\n    const end = Math.min(samples.length, (slice + 1) * size);\n    for (let index = slice * size; index < end; index += stride) loudest = Math.max(loudest, Math.abs(samples[index] ?? 0));\n    peaks.push(loudest);\n  }\n  const top = Math.max(...peaks);\n  return top > 0 ? peaks.map((peak) => Number((peak / top).toFixed(3))) : peaks;\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "A voice note, a recording, a clip of music or narration a person plays and seeks in. The project gives the element its source and, for the waveform, the peaks (computed ahead of time, or with computePeaks for a short clip); without peaks the bar is a flat line of the same size. Offer a Transcript (from captions) for anything spoken. Nothing plays by itself. For video use video-player; for a plain time bar without a waveform use scrubber.",
    "example": "<AudioPlayer aria-label=\"Voice note from Ana\">\n  <AudioPlayerAudio src=\"/note.mp3\" />\n  <AudioPlayerPlay />\n  <AudioPlayerWaveform peaks={peaks} />\n  <AudioPlayerTime />\n  <AudioPlayerRate />\n  <AudioPlayerMute />\n</AudioPlayer>\n\n// Peaks for a short clip, in the browser\nconst peaks = await computePeaks(await (await fetch(\"/note.mp3\")).arrayBuffer(), 64);",
    "client": true
  }
}
