{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bot-audio",
  "title": "Bot Audio",
  "description": "Bot audio output element with a shared volume store, mute toggle, horizontal or vertical volume slider, and a popover volume control.",
  "dependencies": [
    "@pipecat-ai/client-js@^1.14.0",
    "@pipecat-ai/client-react@^1.9.0",
    "lucide-react@^1.41.0",
    "zustand@^5.0.15"
  ],
  "registryDependencies": [
    "button",
    "popover",
    "slider"
  ],
  "files": [
    {
      "path": "src/components/bot-audio.tsx",
      "content": "\"use client\";\n\nimport { RTVIEvent } from \"@pipecat-ai/client-js\";\nimport {\n  usePipecatClientMediaTrack,\n  usePipecatClientTransportState,\n  useRTVIClientEvent,\n} from \"@pipecat-ai/client-react\";\nimport {\n  Volume1Icon,\n  Volume2Icon,\n  VolumeIcon,\n  VolumeXIcon,\n} from \"lucide-react\";\nimport { useCallback, useEffect, useRef } from \"react\";\nimport { create } from \"zustand\";\n\nimport { Button } from \"@/components/ui/button\";\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from \"@/components/ui/popover\";\nimport { Slider } from \"@/components/ui/slider\";\nimport { cn } from \"@/lib/utils\";\n\ntype ButtonProps = React.ComponentProps<typeof Button>;\n\n// Nova's icon-* sizes render a square button; the trigger responds by\n// hiding its label (the label still names the button for screen readers).\nfunction isIconSize(size: ButtonProps[\"size\"]): boolean {\n  return typeof size === \"string\" && size.startsWith(\"icon\");\n}\n\nfunction isAbortError(err: unknown): boolean {\n  return (\n    typeof err === \"object\" &&\n    err !== null &&\n    (err as { name?: unknown }).name === \"AbortError\"\n  );\n}\n\nfunction clampVolume(v: number): number {\n  if (Number.isNaN(v)) return 0;\n  return Math.min(1, Math.max(0, v));\n}\n\ninterface BotAudioState {\n  /** Current bot audio output volume, 0.0 – 1.0. */\n  volume: number;\n  /** Set the bot audio output volume. Values are clamped to [0, 1]. */\n  setVolume: (volume: number) => void;\n}\n\n/**\n * Module-level store for bot audio output volume. Drives the <audio>\n * element rendered by BotAudioOutput; read/written by the volume controls,\n * so any number of control instances stay in sync without prop drilling.\n */\nexport const useBotAudio = create<BotAudioState>()((set) => ({\n  volume: 1,\n  setVolume: (volume) => set({ volume: clampVolume(volume) }),\n}));\n\n// The mounted output element, so unlockBotAudio can reach it from a gesture\n// handler without a ref or context.\nlet outputElement: HTMLAudioElement | null = null;\n\n/**\n * Call synchronously inside the user's gesture (the Connect tap) so iOS\n * Safari treats later playback of the bot track as user-activated. Calls\n * play() on the mounted output element: with no source attached yet it makes\n * no sound, and once the bot track is attached a repeated play() is a no-op,\n * so overlapping calls are harmless. No-op when BotAudioOutput is not\n * mounted. The call may stay pending until a source is attached (Chromium)\n * or reject (no gesture); both are ignored.\n */\nexport function unlockBotAudio(): void {\n  void outputElement?.play().catch(() => undefined);\n}\n\n/** Mount once inside PipecatClientProvider, in place of PipecatClientAudio, to use shared volume controls. */\nexport function BotAudioOutput() {\n  const audioRef = useRef<HTMLAudioElement>(null);\n  const botAudioTrack = usePipecatClientMediaTrack(\"audio\", \"bot\");\n  const volume = useBotAudio((s) => s.volume);\n\n  // Attach the bot's audio track, de-duping on track id so we don't tear\n  // down an already-playing stream.\n  useEffect(() => {\n    const el = audioRef.current;\n    if (!el) return;\n    if (!botAudioTrack) {\n      el.srcObject = null;\n      return;\n    }\n    const existing = el.srcObject as MediaStream | null;\n    if (existing) {\n      const oldTrack = existing.getAudioTracks()[0];\n      if (oldTrack && oldTrack.id === botAudioTrack.id) return;\n    }\n    el.srcObject = new MediaStream([botAudioTrack]);\n    // autoPlay is enough once unlockBotAudio() ran inside the user's tap.\n    // This play() is a diagnostic: without the unlock, iOS Safari refuses\n    // autoPlay silently, and the logged rejection makes that visible.\n    // AbortError means the track was swapped or removed while play() was\n    // pending, not a real failure.\n    void el.play().catch((err: unknown) => {\n      if (isAbortError(err)) return;\n      console.warn(\"BotAudioOutput: play() rejected\", err);\n    });\n  }, [botAudioTrack]);\n\n  useEffect(() => {\n    const el = audioRef.current;\n    outputElement = el;\n    return () => {\n      if (outputElement === el) outputElement = null;\n      if (el) el.srcObject = null;\n    };\n  }, []);\n\n  useEffect(() => {\n    const el = audioRef.current;\n    if (!el) return;\n    el.volume = volume;\n  }, [volume]);\n\n  // setSinkId can reject (unsupported deviceId, permission denied) —\n  // swallow and log so speaker-routing failures stay non-fatal.\n  useRTVIClientEvent(\n    RTVIEvent.SpeakerUpdated,\n    useCallback((speaker: MediaDeviceInfo) => {\n      const el = audioRef.current;\n      if (!el || typeof el.setSinkId !== \"function\") return;\n      el.setSinkId(speaker.deviceId).catch((err: unknown) => {\n        console.warn(\"BotAudioOutput: setSinkId failed\", err);\n      });\n    }, []),\n  );\n\n  return <audio ref={audioRef} autoPlay />;\n}\n\ntype SliderProps = React.ComponentProps<typeof Slider>;\n\n// onVolumeChange is also omitted from the passthrough: React's DOM typings\n// declare it (the native volumechange media event), which would clash with\n// our domain callback.\nexport interface BotVolumeSliderViewProps extends Omit<\n  SliderProps,\n  \"value\" | \"defaultValue\" | \"onValueChange\" | \"onVolumeChange\" | \"min\" | \"max\"\n> {\n  /** Current volume, 0.0 – 1.0. */\n  volume?: number;\n  /** Called with the new volume (0.0 – 1.0). */\n  onVolumeChange?: (volume: number) => void;\n  /** Hide the text label. */\n  noLabel?: boolean;\n  /** Hide the percent readout. */\n  noPercent?: boolean;\n  /** Hide the mute toggle button. */\n  noMuteButton?: boolean;\n  /** Label text; doubles as the slider's accessible name. */\n  label?: string;\n  /** Classes for the root element, not the slider itself. */\n  className?: string;\n}\n\n/** Props-driven volume slider. Muting preserves the last audible volume for restoration. */\nexport function BotVolumeSliderView({\n  volume = 1,\n  onVolumeChange,\n  noLabel = false,\n  noPercent = false,\n  noMuteButton = false,\n  label = \"Bot volume\",\n  orientation = \"horizontal\",\n  step = 0.01,\n  className,\n  ...sliderProps\n}: BotVolumeSliderViewProps) {\n  const pct = Math.round(clampVolume(volume) * 100);\n  const muted = volume <= 0;\n  const vertical = orientation === \"vertical\";\n  const accessibleLabel = label.trim() || \"Bot volume\";\n  const MuteIcon = iconForVolume(volume);\n\n  // Remember the last audible volume so the mute button can restore it.\n  const lastVolume = useRef(volume > 0 ? volume : 1);\n  useEffect(() => {\n    if (volume > 0) lastVolume.current = volume;\n  }, [volume]);\n\n  return (\n    <div\n      data-slot=\"bot-volume-slider\"\n      className={cn(\n        \"flex flex-col gap-2\",\n        vertical && \"items-center\",\n        className,\n      )}\n    >\n      {!noLabel && (\n        <span className=\"text-muted-foreground text-sm\">{label}</span>\n      )}\n      {/* Same DOM both ways: column-reverse puts the percent on top and\n          the mute button at the bottom of a vertical strip. */}\n      <div\n        className={cn(\n          \"flex items-center gap-2\",\n          vertical && \"flex-col-reverse\",\n        )}\n      >\n        {!noMuteButton && (\n          <Button\n            variant=\"ghost\"\n            size=\"icon-sm\"\n            aria-label={muted ? \"Unmute bot\" : \"Mute bot\"}\n            aria-pressed={muted}\n            onClick={() => onVolumeChange?.(muted ? lastVolume.current : 0)}\n          >\n            <MuteIcon />\n          </Button>\n        )}\n        <Slider\n          min={0}\n          max={1}\n          step={step}\n          value={volume}\n          onValueChange={(value) => {\n            const next = Array.isArray(value) ? value[0] : value;\n            if (typeof next === \"number\") onVolumeChange?.(clampVolume(next));\n          }}\n          orientation={orientation}\n          aria-label={accessibleLabel}\n          className={cn(!vertical && \"flex-1\")}\n          {...sliderProps}\n        />\n        {!noPercent && (\n          <span\n            className={cn(\n              \"text-muted-foreground text-xs tabular-nums\",\n              !vertical && \"w-8 text-right\",\n            )}\n          >\n            {pct}%\n          </span>\n        )}\n      </div>\n    </div>\n  );\n}\n\n/**\n * Bot volume slider wired to the useBotAudio store. Requires\n * BotAudioOutput to be mounted for volume changes to be audible.\n */\nexport function BotVolumeSlider(\n  props: Omit<BotVolumeSliderViewProps, \"volume\" | \"onVolumeChange\">,\n) {\n  const { volume, setVolume } = useBotAudio();\n  return (\n    <BotVolumeSliderView\n      volume={volume}\n      onVolumeChange={setVolume}\n      {...props}\n    />\n  );\n}\n\nfunction iconForVolume(volume: number) {\n  if (volume <= 0) return VolumeXIcon;\n  if (volume < 0.34) return VolumeIcon;\n  if (volume < 0.67) return Volume1Icon;\n  return Volume2Icon;\n}\n\nexport interface BotAudioControlViewProps {\n  /** Current volume, 0.0 – 1.0. */\n  volume?: number;\n  /** Called with the new volume (0.0 – 1.0). */\n  onVolumeChange?: (volume: number) => void;\n  /** Disables the trigger button. */\n  disabled?: boolean;\n  /** Hide the volume icon. */\n  noIcon?: boolean;\n  /** Visible label next to the icon. */\n  label?: string;\n  /** Button variant for the trigger. */\n  variant?: ButtonProps[\"variant\"];\n  /**\n   * Button size for the trigger. Icon sizes (\"icon\", \"icon-sm\", …) render\n   * it icon-only: the label is hidden but still read to screen readers.\n   */\n  size?: ButtonProps[\"size\"];\n  /** Popover alignment relative to the trigger. */\n  align?: React.ComponentProps<typeof PopoverContent>[\"align\"];\n  /** Overrides merged onto the popover's volume slider (wins over defaults). */\n  sliderProps?: Partial<BotVolumeSliderViewProps>;\n  /** Classes for the trigger button. */\n  className?: string;\n  /** Extra content rendered inside the trigger, after the label. */\n  children?: React.ReactNode;\n}\n\n/**\n * Bot volume control: a button that opens a popover with the mute toggle,\n * slider, and percent readout (no label). The trigger's icon tracks the\n * current volume level.\n */\nexport function BotAudioControlView({\n  volume = 1,\n  onVolumeChange,\n  disabled = false,\n  noIcon = false,\n  label,\n  variant = \"outline\",\n  size = \"default\",\n  align = \"end\",\n  sliderProps,\n  className,\n  children,\n}: BotAudioControlViewProps) {\n  const Icon = iconForVolume(volume);\n  const iconOnly = isIconSize(size);\n\n  return (\n    <Popover>\n      <PopoverTrigger\n        render={\n          <Button\n            data-slot=\"bot-audio-control\"\n            variant={variant}\n            size={size}\n            disabled={disabled}\n            aria-label={label?.trim() || \"Bot volume\"}\n            className={className}\n          >\n            {!noIcon && <Icon />}\n            {!iconOnly && label}\n            {children}\n          </Button>\n        }\n      />\n      <PopoverContent\n        align={align}\n        className={sliderProps?.orientation === \"vertical\" ? \"w-auto\" : \"w-56\"}\n      >\n        <BotVolumeSliderView\n          noLabel\n          volume={volume}\n          onVolumeChange={onVolumeChange}\n          {...sliderProps}\n        />\n      </PopoverContent>\n    </Popover>\n  );\n}\n\n/**\n * Bot volume control wired to the useBotAudio store and transport state.\n * Disabled while disconnected. Requires BotAudioOutput to be mounted.\n * Must be rendered inside a PipecatClientProvider.\n */\nexport function BotAudioControl(\n  props: Omit<\n    BotAudioControlViewProps,\n    \"volume\" | \"onVolumeChange\" | \"disabled\"\n  >,\n) {\n  const { volume, setVolume } = useBotAudio();\n  const transportState = usePipecatClientTransportState();\n  const disabled =\n    transportState === \"disconnected\" || transportState === \"initializing\";\n\n  return (\n    <BotAudioControlView\n      volume={volume}\n      onVolumeChange={setVolume}\n      disabled={disabled}\n      {...props}\n    />\n  );\n}\n",
      "type": "registry:component",
      "target": "components/pipecat/bot-audio.tsx"
    }
  ],
  "docs": "Mount BotAudioOutput once (in place of PipecatClientAudio), then use BotAudioControl or BotVolumeSlider anywhere. Render inside a PipecatClientProvider.",
  "categories": [
    "voice"
  ],
  "type": "registry:component"
}