Skip to content
Mostafashadow1Public

About

UI sound effects for web apps, synthesized with the Web Audio API. No audio files, ~2.5 KB, SSR-safe.

Topics

Resources

Stars

9 stars

Watchers

0 watching

Forks

Repository files navigation

Tonely Cover Banner

Zero-asset, ultra-lightweight synthesized UI sound design system for modern web apps.
No MP3s. No WAV files. No network latency. 100% procedural Web Audio API synthesis.

License MIT Bundle Size Zero Assets Zero Latency SSR Safe TypeScript Strict


When to use Tonely

  • The app needs sound feedback for actions: form saved, payment done, error, button click, toggle, delete, new notification.
  • You want sounds without shipping .mp3/.wav files or handling audio asset paths.
  • You need it to be safe in Next.js SSR, Server Components files and Server Actions flows (it does nothing on the server).
  • You want toast notifications (Sonner, shadcn/ui) to play a matching sound.

Not for: You need to play music, voice, or a specific recorded sound file. Use HTMLAudioElement or Howler.js. You need audio that plays without any prior user interaction. Browsers block that for every library.

Using an AI coding agent? This package ships an AGENTS.md and an llms.txt with usage rules and examples. Agents with the Context7 MCP can fetch these docs directly.


πŸ’‘ Why Tonely?

Modern SaaS products (Stripe, Slack, Linear, Apple Pay) feel extraordinarily polished because of multi-sensory micro-interactions. When an action succeeds, auditory feedback confirms completion instantly without forcing the user to stare at a spinner or scan for a toast notification.

However, 95% of developers avoid adding audio to their web applications because:

  1. Asset Burden: Managing .mp3 or .wav files, licensing, CDN uploads, and Next.js / Vite asset path headaches.
  2. First-Play Network Lag: Audio files must be fetched over the network; the first click sounds delayed (150–400ms lag) or misses entirely.
  3. Browser Autoplay Restrictions: Browsers suspend audio playback unless properly unlocked on user gestures.
  4. SSR Crashes: Libraries crash during Next.js Server-Side Rendering when window or AudioContext is undefined.

The Tonely Solution:

  • 0 KB Audio Assets: Every chime, click, pop, and tone is synthesized procedurally in real-time using native browser oscillators and gain envelopes.
  • ~2.5 KB gzip: Smaller than a typical hero image thumbnail.
  • Zero Network Latency: Sounds trigger in under 1ms because zero bytes are downloaded.
  • 100% SSR-Safe: Safe to import and call anywhere in Next.js (Server Components, Server Actions, Route Handlers). It gracefully acts as a silent no-op on the server.
  • Dynamic Themes: Adjust pitch, volume, and acoustic palettes (Modern SaaS, Crystal Glass, Subtle Minimal, Bouncy Playful, Chiptune Retro) on the fly.

πŸ“¦ Installation

# pnpm
pnpm add tonely

# npm
npm install tonely

# yarn
yarn add tonely

# bun
bun add tonely

⚑ Quick Start

1. Vanilla JavaScript / TypeScript

import { tonely } from "tonely";

// 1. Play individual cues
tonely.success(); // 🎢 Rising harmonic major chord (HTTP 200)
tonely.error(); // ⚠️ Gentle warning double-tone (HTTP 4xx/5xx)
tonely.click(); // πŸ–±οΈ Ultra-tight 25ms tactile click

// 2. Map directly from HTTP Status Code
const res = await fetch("/api/orders", { method: "POST" });
tonely.fromStatus(res.status); // 200 -> success, 400/500 -> error, 300 -> info

// 3. Or wrap fetch automatically
const enhancedFetch = tonely.wrapFetch();
await enhancedFetch("/api/checkout"); // Plays success or error automatically!

2. React / Next.js Client Component

"use client";

import { useTonely } from "tonely/react";

export function CheckoutButton() {
  const { success, error, click } = useTonely({ theme: "glass" });

  const handleCheckout = async () => {
    click(); // Instant tactile response on click
    try {
      await processPayment();
      success(); // Harmonic chime confirmation
    } catch (err) {
      error(); // Gentle warning alert
    }
  };

  return (
    <button onClick={handleCheckout} className="btn-primary">
      Pay Now
    </button>
  );
}

3. Next.js 15 Server Actions

Tonely is designed with senior-level isomorphic safety. You can trigger audio safely inside transitions or after server action resolutions:

"use client";

import { useTransition } from "react";
import { tonely } from "tonely";
import { updateBillingAction } from "@/actions/billing";

export function BillingSettings() {
  const [isPending, startTransition] = useTransition();

  const handleUpdate = (formData: FormData) => {
    tonely.click();
    startTransition(async () => {
      const response = await updateBillingAction(formData);
      if (response.success) {
        tonely.success();
      } else {
        tonely.error();
      }
    });
  };

  return (
    <form action={handleUpdate}>
      {/* Inputs */}
      <button disabled={isPending}>Save Billing</button>
    </form>
  );
}

4. Sonner & Shadcn UI Toasts Integration

Create a sound-enhanced toast helper with just 10 lines of code:

import { toast as baseToast } from "sonner";
import { tonely } from "tonely";

export const toast = {
  success: (message: string) => {
    tonely.success();
    return baseToast.success(message);
  },
  error: (message: string) => {
    tonely.error();
    return baseToast.error(message);
  },
  warning: (message: string) => {
    tonely.warning();
    return baseToast.warning(message);
  },
  info: (message: string) => {
    tonely.info();
    return baseToast.info(message);
  },
};

5. Vue 3 (Composition API)

<script setup>
import { tonely } from "tonely";

async function handleSave() {
  tonely.click();
  try {
    await saveDocument();
    tonely.success();
  } catch {
    tonely.error();
  }
}
</script>

<template>
  <button @click="handleSave">Save Changes</button>
</template>

🎡 Sound Catalog

All sounds are synthesized procedurally using precision oscillators and exponential ADSR envelopes:

Method Musical Profile Ideal Use Case
tonely.success() Rising major chord (C5 -> E5 -> G5) HTTP 200 OK, form saved, mutation done
tonely.error() Gentle dissonant drop (E4 -> C4) HTTP 4xx/5xx, form validation failed
tonely.warning() Dual-tone presence ping (A4 -> C#5) Unsaved changes, confirmation alerts
tonely.info() Soft crisp sine chime (E5 / 659 Hz) Notification badge, tooltip, incoming message
tonely.click() Micro-transient tactile click (25ms) Primary buttons, tabs, segmented controls
tonely.pop() Upward frequency sweep (380 -> 950 Hz) Modals opening, dropdown menus, badges
tonely.toggle(active) Dynamic switch (Rises for ON, drops for OFF) Toggle switches, checkboxes, theme toggle
tonely.delete() Descending muted tone (G4 -> D4) Trash actions, item removed, discard draft
tonely.glass() High-Q resonant crystal chime (C6) Premium rewards, milestone unlocks, payments
tonely.bubble() Liquid droplet modulation Likes, hearts, reactions, bookmarking

🎨 Sound Themes (Palettes)

Switch soundscapes globally or per sound invocation:

  • modern (Default): Clean, balanced, elegant harmonics tailored for SaaS applications.
  • glass: Apple-like crystal shimes and resonant crystalline textures.
  • minimal: Subtle micro transients with zero auditory fatigue.
  • playful: Bouncy, rounded curves for games, social, or consumer products.
  • retro: Chiptune 8-bit square waves for arcade-style nostalgia.
// Per-sound theme override
tonely.success({ theme: "glass", volume: 0.8 });

// Global theme configuration
tonely.setTheme("minimal");

πŸ€– AI Prompts Hub (Cursor, Claude, v0, Antigravity)

Use these copy-paste prompts with your AI assistant to instrument your application in seconds:

Prompt: Integrate with Sonner / Shadcn UI Toasts
Please integrate the 'tonely' library into my React/Next.js project.
Wrap my toast notification helper (Sonner / Shadcn UI) so that:
- toast.success() plays tonely.success()
- toast.error() plays tonely.error()
- toast.warning() plays tonely.warning()
- toast.info() plays tonely.info()
Ensure it is 100% SSR-safe and works seamlessly inside client components.
Prompt: Sound Feedback for Forms and Mutations
Please enhance my form submissions using 'tonely':
1. When the user clicks the submit button, trigger tonely.click()
2. If the mutation or API response succeeds (HTTP 200), play tonely.success()
3. If the form validation fails or the server returns an error, play tonely.error()
Import { tonely } from 'tonely' and keep all audio calls strictly client-side.
Prompt: Automatic Fetch / Axios Status Interceptor
Configure an API response interceptor using 'tonely':
- Status 2xx -> tonely.fromStatus(res.status)
- Status 4xx / 5xx -> tonely.fromStatus(res.status)
Ensure non-blocking execution and graceful handling across all endpoints.

πŸ“Š Benchmark & Comparison

Feature MP3 / WAV Assets Base64 Inlining Tonely (Web Audio API)
Audio File Size 50 KB – 300 KB+ 30 KB – 80 KB 0 KB (Zero assets!)
JS Library Size ~15 KB + assets ~40 KB + assets ~2.5 KB (gzipped)
First Play Latency 150ms – 400ms 10ms < 1ms (Instant)
HTTP Requests 1 per sound file 0 0
SSR Compatibility Throws on window Throws on window 100% Isomorphic Safe No-op
Dynamic Pitch & Themes Requires new audio files Requires new audio files Realtime mathematical control

πŸ› οΈ Monorepo Structure

tonely/
β”œβ”€β”€ packages/
β”‚   └── tonely/           # Core library (NPM: tonely)
β”‚       β”œβ”€β”€ src/
β”‚       β”‚   β”œβ”€β”€ core/     # AudioEngine, AudioContext singleton, Autoplay unlocker
β”‚       β”‚   β”œβ”€β”€ presets/  # Procedural synthesizers (success, error, click, etc.)
β”‚       β”‚   β”œβ”€β”€ react/    # useTonely hook & TonelyProvider
β”‚       β”‚   └── utils/    # SSR safety guards & Fetch status wrappers
β”‚       └── tests/        # Vitest suite
└── apps/
    └── website/          # Next.js 15 interactive documentation & soundboard

πŸ“„ License

MIT Β© Mostafa Mohamed Abdalla

About

UI sound effects for web apps, synthesized with the Web Audio API. No audio files, ~2.5 KB, SSR-safe.

Topics

Resources

Stars

9 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages