Categories: CSSScriptWeb Design

Add UI Sound Effects to Web Apps With Tiks and Web Audio API

tiks is a JavaScript sound effect library that generates iOS-like UI audio feedback at runtime through the Web Audio API.

It generates clicks, toggles, notifications, and nine other interaction sounds using oscillators, noise buffers, and gain envelopes.

No audio files are included within the library. Every sound is computed on the fly from math alone.

Features:

  • 10 UI sounds: clicks, toggles, success states, errors, warnings, hovers, pops, transitions, and notifications.
  • Two built-in audio themes that change the tonal character of every sound across the whole library at once.
  • Full custom theme support with control over base frequency, oscillator type, noise color, filter parameters, attack, and decay.
  • Runtime volume control and global mute toggle.
  • A React hook that auto-initializes the audio context on mount and returns stable method references.
  • A Vue composable with the same auto-initialization behavior and identical API shape.
  • Tree-shakeable named exports.
  • Automatic AudioContext resume on first user gesture.
  • A prefers-reduced-motion option that mutes all sounds automatically for users who request reduced motion.

Use Cases:

  • Add tactile audio feedback to form controls like toggles, checkboxes, and dropdowns in a design system.
  • Play unique notification and error sounds in a dashboard app to reinforce visual status changes.
  • Provide keyboard navigation audio cues in an accessibility-conscious web application.
  • Bring a native app feel to a Progressive Web App where audio assets would inflate the bundle size.

How To Use It

1. Install tik with NPM.

npm install @rexa-developer/tiks

2. Import tiks and call init() inside a user gesture handler.

import { tiks } from '@rexa-developer/tiks';

// Call init() once, ideally on the first user gesture
document.addEventListener('click', () => {
  tiks.init();
}, { once: true });

3. Play UI sounds:

// Short crisp tap, ~30ms
tiks.click();

// Rising pitch snap for an "on" state
tiks.toggle(true);

// Falling pitch snap for an "off" state
tiks.toggle(false);

// Two-note rising chime for a completed action
tiks.success();

// Gentle buzz for a failed validation
tiks.error();

// Double-tap tone for a soft alert
tiks.warning();

// Near-silent tick for mouse or keyboard hover feedback
tiks.hover();

// Short bubble pop for a dismissal or removal
tiks.pop();

// Quick whoosh for a panel or page transition
tiks.swoosh();

// Bright ping for an incoming notification
tiks.notify();

4. Set sound themes:

// Initialize with the default warm, rounded theme
tiks.init({ theme: 'soft' });

// Initialize with the sharper, more mechanical theme
tiks.init({ theme: 'crisp' });

// Switch theme at runtime after initialization
tiks.setTheme('crisp');

5. Create your own sound themes:

  • name (string): A unique identifier for the theme.
  • baseFreq (number): The root frequency in Hz from which all sounds derive their pitch relationships.
  • noiseColor ('white' | 'pink'): Selects the noise type for transient and click sounds.
  • oscType (OscillatorType): The oscillator waveform. Accepts 'sine', 'triangle', 'square', or 'sawtooth'.
  • filterFreq (number): The center frequency in Hz for the bandpass filter applied to click and transient sounds.
  • filterQ (number): The resonance (Q factor) of the bandpass filter.
  • attack (number): Attack time in seconds. Controls how fast each sound rises to peak amplitude.
  • decay (number): A multiplier applied to the base duration of each sound. 1.0 is normal, 0.5 produces snappier sounds.
  • brightness (number): The cutoff frequency in Hz for the highpass filter. Higher values produce a brighter character.
import { tiks, defineTheme } from '@rexa-developer/tiks';

// Define a branded theme with a higher base frequency and triangle wave
const brandTheme = defineTheme({
  name: 'brand',
  baseFreq: 520,
  oscType: 'triangle',
  decay: 0.75,
});

tiks.init({ theme: brandTheme });

6. Available init options:

  • theme (string | ThemeObject): Sets the active audio theme. Accepts 'soft', 'crisp', or a custom theme object returned by defineTheme. Defaults to 'soft'.
  • volume (number): Sets the master playback volume on a scale from 0.0 to 1.0. Defaults to 0.3.
  • muted (boolean): Starts the library in a muted state when set to true. Defaults to false.
  • respectReducedMotion (boolean): When true, auto-mutes the library if the user’s OS has prefers-reduced-motion: reduce set. Defaults to false.

7. More API methods:

// Set master volume (0.0 to 1.0)
tiks.setVolume(0.6);

// Mute all sounds globally
tiks.mute();

// Unmute after a previous mute call
tiks.unmute();

// Switch the active theme at runtime
tiks.setTheme('soft');

React Integration

The useTiks hook initializes the audio context automatically when the component mounts.

import { useTiks } from '@rexa-developer/tiks/react';

function SaveButton() {
  // Destructure only the sounds you need
  const { click, success, error } = useTiks({ theme: 'crisp' });

  async function handleSave() {
    click(); // play tap on button press
    try {
      await saveData();
      success(); // play chime on completion
    } catch {
      error(); // play buzz on failure
    }
  }

  return <button onClick={handleSave}>Save Project</button>;
}

Vue Integration

<script setup>
import { useTiks } from '@rexa-developer/tiks/vue';

// Auto-initializes on mount
const { click, toggle, notify } = useTiks({ theme: 'soft' });

function handleToggle(newState) {
  toggle(newState); // pitch direction reflects the boolean state
}
</script>

<template>
  <button @click="click">Tap me</button>
  <button @click="() => handleToggle(true)">Enable</button>
</template>

CDN Usage

<script type="module">
  import { tiks } from 'https://esm.sh/@rexa-developer/tiks';

  // Wire init to the first interaction
  document.querySelector('#action-btn').addEventListener('click', () => {
    tiks.init();
    tiks.click();
  });
</script>

Tree-Shakeable Imports

Import individual sounds to keep your bundle small.

// Pull in only the functions this module needs
import { init, click, success, error } from '@rexa-developer/tiks';

init({ theme: 'soft', volume: 0.4 });

document.querySelector('#submit-btn').addEventListener('click', () => {
  click();
});

FAQs:

Q: Why do I get no sound on the first click?
A: The browser’s autoplay policy has suspended the AudioContext before a gesture occurs. Call tiks.init() inside a user interaction handler (a click or keydown callback). The library handles subsequent resumes automatically, but the first call must happen inside a gesture.

Q: Can I use tiks with React without the useTiks hook?
A: Yes. Import the tiks singleton directly from @rexa-developer/tiks and call tiks.init() inside a useEffect with an empty dependency array.

Q: Do volume and muted settings sync across multiple useTiks hooks in React?
A: Volume and muted state are global on the underlying audio engine. If two hooks pass different volume values, the last-mounted hook wins. Theme, on the other hand, is per-hook instance.

Q: Does tiks replace a full audio library for music or long clips?
A: No. tiks fits short interaction feedback. Pick a broader audio library if your app needs long playback, streaming, or asset management.

The post Add UI Sound Effects to Web Apps With Tiks and Web Audio API appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Planned Sydney Sweeney Cameo Reportedly Chopped from The Devil Wears Prada 2

A short scene featuring Sydney Sweeney has reportedly been left out of the final cut…

13 minutes ago

Planned Sydney Sweeney Cameo Reportedly Chopped from The Devil Wears Prada 2

A short scene featuring Sydney Sweeney has reportedly been left out of the final cut…

13 minutes ago

Vanilla JS Offcanvas Side Menu – Mobile Swipe Menu

Mobile Swipe Menu is a vanilla JavaScript library that creates touch-enabled off-canvas side menus for…

2 hours ago

New Bills Aim to Boost Housing Supply Across Michigan

LANSING, MI (WOWO) A broad coalition of business groups, housing advocates and environmental organizations is…

2 hours ago

Michigan Lawmakers Advance Mental Health Reform Efforts

LANSING, MI (WOWO) Michigan lawmakers are advancing a series of proposals aimed at reforming the…

2 hours ago

Unauthorized Group Gains Access to Anthropic’s Exclusive Cyber Tool Mythos

A group of unauthorized users has reportedly breached access controls surrounding Claude Mythos Preview, Anthropic’s…

2 hours ago

This website uses cookies.