Aaditya

Oscilloscope

Component

About

An oscilloscope for voice and audio: a time trace or an XY figure. Draws a built in voice like signal, or any microphone or audio element through an AnalyserNode.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Oscilloscope to your project and fits it to your theme.

Code

How Oscilloscope is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { cn } from "@/lib/utils"
import { Toggle } from "@base-ui/react/toggle"
import { ToggleGroup } from "@base-ui/react/toggle-group"
import { Oscilloscope, OscilloscopeMode } from "@/components/ui/oscilloscope"

const reducedMotion = () =>
  typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches

/**
 * Steps through `values` on a timer, so a 21st preview (and its cover video) shows every option
 * without a click. Picking a value stops the tour. Reduced motion never starts it.
 */
function useCycle<T>(values: readonly T[], ms: number) {
  const [index, setIndex] = React.useState(0)
  const [held, setHeld] = React.useState(false)
  React.useEffect(() => {
    if (held || reducedMotion()) return
    const id = window.setInterval(() => setIndex((n) => (n + 1) % values.length), ms)
    return () => window.clearInterval(id)
  }, [held, values.length, ms])
  const pick = React.useCallback(
    (value: T) => {
      setHeld(true)
      setIndex(Math.max(0, values.indexOf(value)))
    },
    [values],
  )
  return [values[index] as T, pick] as const
}

const MODES = [
  { value: "time", label: "Time" },
  { value: "xy", label: "XY" },
] as const satisfies readonly { value: OscilloscopeMode; label: string }[]

const MODE_VALUES = MODES.map((m) => m.value)

/**
 * A voice-like signal over time, then as an XY figure, in turn, its gain swelling like speech.
 * Pass an AnalyserNode to draw a real microphone or audio element instead.
 */
/** Syllables and pauses, like someone talking: the gain swells and falls a few times a second. */
function useSpeechGain() {
  const [gain, setGain] = React.useState(1)
  React.useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
    const start = performance.now()
    const id = window.setInterval(() => {
      const t = (performance.now() - start) / 1000
      const syllable = Math.abs(Math.sin(t * Math.PI * 2.6))
      const phrase = 0.55 + 0.45 * Math.sin(t * Math.PI * 0.45)
      setGain(0.25 + 1.15 * syllable * phrase)
    }, 50)
    return () => window.clearInterval(id)
  }, [])
  return gain
}

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

/** A labeled segmented control on Base UI ToggleGroup. One value is always selected. */
function Segmented<T extends string>({
  label,
  value,
  onValueChange,
  options,
  className,
}: {
  label: string
  value: T
  onValueChange: (value: T) => void
  options: readonly { value: T; label: string }[]
  className?: string
}) {
  return (
    <div className={cn("flex max-w-full min-w-0 flex-col gap-1.5", className)}>
      <span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle) font-medium">{label}</span>
      <ToggleGroup
        value={[value]}
        onValueChange={(next) => {
          const picked = next[0] as T | undefined
          if (picked) onValueChange(picked)
        }}
        aria-label={label}
        className="bg-(color:--chatcn-fill) rounded-(--chatcn-radius-md) chatcn-scroll flex h-8 w-fit max-w-full items-center gap-0.5 overflow-x-auto p-0.5 pointer-coarse:h-11"
      >
        {options.map((option) => (
          <Toggle
            key={option.value}
            value={option.value}
            className={cn(
              "chatcn-focus rounded-(--chatcn-radius-sm) text-[0.8125rem]/[1.25rem] inline-flex h-full shrink-0 items-center px-2.5 font-medium whitespace-nowrap",
              "text-(color:--chatcn-fg-subtle) ease-(--chatcn-ease-standard) transition-[color,background-color,box-shadow] duration-150",
              "hover:text-(color:--chatcn-fg) data-[pressed]:bg-(color:--chatcn-card) data-[pressed]:text-(color:--chatcn-fg) data-[pressed]:shadow-(--chatcn-shadow-xs)",
            )}
          >
            {option.label}
          </Toggle>
        ))}
      </ToggleGroup>
    </div>
  )
}

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

export default function OscilloscopePreview() {
  const [mode, setMode] = useCycle<OscilloscopeMode>(MODE_VALUES, 1600)
  const gain = useSpeechGain()
  return (
    <FitFrame>
      <div className="flex w-full flex-col items-center justify-center gap-6 p-6">
        <div className="flex w-full max-w-xl flex-col gap-4">
          <Oscilloscope mode={mode} gain={gain} label="Voice signal" />
          <div data-fit-hide>
            <Segmented label="Mode" value={mode} onValueChange={setMode} options={MODES} />
          </div>
        </div>
        <MoreOn slug="oscilloscope">Plug in a microphone or any audio node. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aaditya

View all
  • Pixel Orb

    Pixel Orb

    9
  • Dither Orb

    Dither Orb

    9
  • Dot Matrix Loader

    Dot Matrix Loader

    8
  • Halftone Loader

    Halftone Loader

    6
  • ASCII 3D

    ASCII 3D

    5
  • Wireframe Globe

    Wireframe Globe

    5
  • Audio Visualizer

    Audio Visualizer

    5
  • LED Matrix

    LED Matrix

    4

Explore more

Part of chatcn — browse the full library on 21st.dev.