Toggle Sound

A two-stage snap, rising for on and falling for off.

Preview

"use client";

import { useState } from "react";
import { useSound } from "@/lib/sound";
import { toggleOffSound, toggleOnSound } from "@/lib/sounds/toggle";

export function ToggleSoundUsage() {
  const [on, setOn] = useState(false);
  const playOn = useSound(toggleOnSound);
  const playOff = useSound(toggleOffSound);
  return (
    <button
      type="button"
      aria-pressed={on}
      onClick={() => {
        if (on) playOff();
        else playOn();
        setOn(!on);
      }}
      className="inline-flex h-9 items-center rounded-full border border-border bg-card px-4 text-sm font-medium text-foreground transition-colors aria-pressed:border-primary aria-pressed:bg-primary aria-pressed:text-primary-foreground"
    >
      {on ? "On" : "Off"}
    </button>
  );
}

Install

Add it with the shadcn CLI, or copy the source manually.

$ bunx --bun shadcn add @beui/toggle-sound

API Reference

sound.play(options)

volume?
number

0 to 1, multiplied with the SoundProvider volume.

Default1
pitch?
number

Pitch multiplier; 1 is the designed pitch.

Default1

useSound(sound, options)

enabled?
boolean

False makes play do nothing, for a component's sound prop.

Defaulttrue
volume?
number

0 to 1 for this sound, on top of the provider volume.

Default1

Updated