Documentation

Introduction

react-sounds provides a library of ready-to-play sound effects for your React applications, designed to be lightweight, easy to use, and flexible. It's built on top of Howler.js and provides a simple API for playing sounds in your React apps.

Coming from use-sound? See use-sound vs react-sounds for the differences and how to switch. New to sound in React? Start with how to play sounds in React.

Key Features

  • 🔊 Extensive Sound Library: Organized by category (ui, notification, game, etc.).
  • 🎵 Custom Sounds: Use your own sound files by requiring them directly.
  • 🪶 Lightweight: Only JS wrappers included; audio files hosted on CDN.
  • 🏗️ Lazy Loading: Sounds fetched only when needed.
  • 📦 Offline Support: Local sound files with automatic fallback to CDN.
  • 🎯 Simple API: Easy-to-use hooks and components.
  • 💾 Persistent Settings: Sound preferences saved to localStorage.
  • 🎮 Controls: Play, pause, resume and stop with sound state management.

Installation

Install the library and its peer dependency, Howler.js:

npm install react-sounds howler
# or
yarn add react-sounds howler

Note: Howler.js is a required peer dependency.

Basic Usage

Playing a Sound with the useSound Hook

The useSound hook is the primary way to interact with sounds.

import { useSound } from 'react-sounds';

function Button() {
  const { play } = useSound('ui/button_soft');
  
  return (
    <button onClick={() => play()}>
      Click Me
    </button>
  );
}

Using Custom Sound Files

You can use your own custom sound files by requiring them directly:

import { useSound } from 'react-sounds';
import customClickSound from '../assets/sounds/click.mp3';

function Button() {
  // Use a custom sound file by requiring it
  const { play } = useSound(customClickSound);
  
  return (
    <button onClick={() => play()}>
      Custom Sound Button
    </button>
  );
}

Using Sounds from a URL

Any MP3 URL works too. If the file is on another domain, the server must send CORS headers (Access-Control-Allow-Origin).

const { play } = useSound('https://cdn.example.com/sounds/whoosh.mp3');

Direct Sound Playing with playSound

For simple, one-off sound playback without needing state or controls.

import { playSound } from 'react-sounds';
import customSound from '../assets/sounds/notification.mp3';

function Button() {
  // You can use built-in sounds
  const handleClick = () => playSound('ui/button_soft');
  
  // Or your own custom sounds
  const handleCustomSound = () => playSound(customSound);
  
  return (
    <div>
      <button onClick={handleClick}>
        Built-in Sound
      </button>
      <button onClick={handleCustomSound}>
        Custom Sound
      </button>
    </div>
  );
}

Setup with SoundProvider

For best results, wrap your application with the SoundProvider component. This allows control of sound enabled state, preloads sounds, and establishes the sound context.

import { SoundProvider } from 'react-sounds';
import customSound from '../assets/sounds/startup.mp3';

function App() {
  return (
    <SoundProvider 
      // Optional: preload both built-in and custom sounds
      preload={['ui/button_soft', 'notification/success', customSound]} 
      // Optional: set initial sound enabled state (defaults to true)
      initialEnabled={true}
    >
      <YourApp />
    </SoundProvider>
  );
}

Core API

The useSound Hook

The useSound hook provides full control over sound playback. It works with both built-in sound names and custom sound files.

import { useSound } from 'react-sounds';
import customSound from '../assets/sounds/custom.mp3';

function SoundPlayer() {
  // Using a built-in sound
  const { 
    play,   // Function to play the sound
    stop,   // Function to stop the sound
    pause,  // Function to pause the sound
    resume, // Function to resume a paused sound
    isPlaying, // Boolean indicating if sound is currently playing
    isLoaded,  // Boolean indicating if sound has been loaded
    checkPermission, // Check browser audio permission status
  } = useSound('ui/button_soft');
  
  // Using a custom sound file with options
  const { play: playCustom } = useSound(customSound, { 
    volume: 0.8, 
    rate: 1.2,
    loop: false
  });
  
  return (
    <div>
      <button onClick={() => play()} disabled={!isLoaded}>Play Built-in Sound</button>
      <button onClick={() => playCustom()}>Play Custom Sound</button>
      <button onClick={() => pause()} disabled={!isPlaying}>Pause</button>
      <button onClick={() => resume()} disabled={isPlaying}>Resume</button>
      <button onClick={() => stop()}>Stop</button>
    </div>
  );
}

React Components

For declarative sound playback within your components.

import { Sound, SoundButton, SoundProvider } from 'react-sounds';

// Component that plays a sound on mount, unmount, or manually
function NotificationBanner() {
  return (
    <Sound 
      name="notification/alert"
      trigger="mount" // 'mount', 'unmount', or 'none'
      options={{ volume: 0.8 }}
      onLoad={() => console.log('Sound loaded')}
      onPlay={() => console.log('Sound playing')}
      onStop={() => console.log('Sound stopped')}
      onError={(error) => console.error('Sound error:', error)}
    >
      <div className="banner">Notification Banner</div>
    </Sound>
  );
}

import customNotification from '../assets/sounds/notification.mp3';

// Button that plays a sound when clicked
function ActionButton({ onClick }) {
  return (
    <SoundButton 
      sound="ui/button_soft" // Can also use custom sound import
      soundOptions={{ volume: 0.7 }}
      onClick={onClick}
      onSoundError={(error) => console.error('Sound error:', error)}
    >
      Action Button
    </SoundButton>
  );
}

Utility Hooks

Additional hooks for specific sound use cases.

import { useSoundOnChange, useSoundEnabled } from 'react-sounds';

// Play a sound when a value changes
function Counter() {
  const [count, setCount] = useState(0);
  
  // Play a sound whenever count changes
  useSoundOnChange('ui/increment', count, { volume: 0.5 });
  
  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

// Access and control the global sound enabled state
function SoundToggle() {
  // Must be used within a SoundProvider
  const [enabled, setEnabled] = useSoundEnabled();
  
  return (
    <button onClick={() => setEnabled(!enabled)}>
      Sounds: {enabled ? 'On' : 'Off'}
    </button>
  );
}

Advanced Usage

Configuring CDN URL

Configure where built-in sound files are loaded from. Note: This doesn't affect custom sound files that you import directly.

import { setCDNUrl, getCDNUrl } from 'react-sounds';

// Set a custom CDN base URL for built-in sounds
setCDNUrl('https://your-cdn.com/sounds');

// Get the current CDN URL
const currentUrl = getCDNUrl();

Sound Enabling/Disabling

Globally enable or disable all sounds. The setting is automatically persisted in localStorage.

import { setSoundEnabled, isSoundEnabled } from 'react-sounds';

// Check if sounds are enabled
const enabled = isSoundEnabled();

// Disable all sounds
setSoundEnabled(false);

// Re-enable sounds
setSoundEnabled(true);

Checking Audio Permission

Check if the browser allows audio playback before attempting to play. This is useful for showing UI hints or handling browsers that block autoplay.

import { checkAudioPermission } from 'react-sounds';
import { useSound } from 'react-sounds';

// Standalone usage
async function checkAudio() {
  const status = await checkAudioPermission();
  // status is one of:
  //   'granted'     - audio playback is allowed
  //   'prompt'      - user may need to interact before audio works
  //   'unavailable' - audio is not supported or blocked
  console.log('Audio permission:', status);
}

// Via the useSound hook
function SoundPlayer() {
  const { play, checkPermission } = useSound('ui/button_soft');

  const handlePlay = async () => {
    const status = await checkPermission();
    if (status === 'granted') {
      play();
    } else {
      console.log('Audio not available:', status);
    }
  };

  return <button onClick={handlePlay}>Play Sound</button>;
}

Preloading Sounds

Preload sounds to ensure they are ready for immediate playback.

import { preloadSounds } from 'react-sounds';
import customSound from '../assets/sounds/custom.mp3';

// Preload multiple sounds at once (both built-in and custom)
preloadSounds(['ui/button_soft', 'notification/success', customSound])
  .then(() => console.log('All sounds preloaded'))
  .catch((error) => console.error('Error preloading sounds:', error));

Custom Sound Options

Customize sound playback with various options.

import { useSound, playSound, SoundOptions } from 'react-sounds';
import customExplosion from '../assets/sounds/explosion.mp3';

// SoundOptions interface:
// {
//   volume?: number;  // 0.0 to 1.0
//   rate?: number;    // playback speed (1.0 is normal)
//   loop?: boolean;   // whether to loop the sound
// }

function SoundPlayer() {
  const { play } = useSound(customExplosion);
  
  const playWithOptions = () => {
    // Play with custom options
    play({ 
      volume: 0.8,  // 80% volume
      rate: 1.2,    // 20% faster
      loop: false   // don't loop
    });
    
    // Direct play with options
    playSound('ui/button_soft', { volume: 0.5 });
  };
  
  return <button onClick={playWithOptions}>Play with Options</button>;
}

CLI Tool for Offline Sounds

Use the CLI tool to download sounds for offline use or explore available sounds.

# List all available sounds
npx react-sounds-cli list

# Download specific sounds for offline use
npx react-sounds-cli pick ui/button_soft notification/success

# Download sounds to a custom directory
npx react-sounds-cli pick ui/button_soft --output=./public/sounds

Sound Packs

A sound pack is a manifest.json that lists MP3 files by name. Add one with the CLI, which also generates TypeScript types so pack sound names autocomplete like built-in ones. You can find ready-made packs, or generate your own sounds, on openfoley:

# Use the pack's files from where they are hosted
npx react-sounds-cli add https://openfoley.com/c/ui-sounds

# Or copy the files into your app (public/sounds/ui-sounds)
npx react-sounds-cli add https://openfoley.com/c/ui-sounds --download

Register the pack once and play its sounds as "pack-name/sound":

import { SoundProvider, useSound } from 'react-sounds';
import uiSounds from './sounds/ui-sounds.json';

function App() {
  return (
    <SoundProvider packs={[uiSounds]}>
      <SaveButton />
    </SoundProvider>
  );
}

function SaveButton() {
  const { play } = useSound('ui-sounds/bright-success-chime');
  return <button onClick={() => play()}>Save</button>;
}

// Without a provider: registerSounds(uiSounds)
// Self-hosting the files elsewhere: registerSounds(uiSounds, { baseUrl: 'https://my-cdn.com/ui-sounds' })

To turn your own folder of MP3s into a pack you can host anywhere:

npx react-sounds-cli pack ./my-sounds --name=my-sounds
# writes ./my-sounds/manifest.json
{
  "name": "my-sounds",
  "version": "1",
  "baseUrl": "https://cdn.example.com/my-sounds",
  "sounds": {
    "click": { "src": "click.mp3", "duration": 0.04, "license": "CC0-1.0" },
    "menu/open": { "src": "menu/open.mp3" }
  }
}

baseUrl is optional: without it, files are resolved relative to where the manifest is hosted (or /sounds/<name> at runtime). Only src is required per sound. Files must be MP3, and should never change at the same URL.

Add Sounds with Your AI Agent

openfoley has an MCP server, so coding agents like Claude Code and Cursor can search for sounds and wire them up with react-sounds for you. Just ask, e.g. “add a soft click to the buttons”:

claude mcp add --transport http openfoley https://openfoley.com/mcp

Searching works without an account. To let your agent generate new sounds and build sound packs, add an openfoley API token.

TypeScript Support

react-sounds provides TypeScript definitions for all exported functions, hooks, components, and types.

Sound Types

Sounds can be either built-in sound names or custom imported sound files.

import type { 
  LibrarySoundName,         // Union of all built-in sound categories
  UiSoundName,       // UI sounds (clicks, toggles, etc.)
  GameSoundName,     // Game sounds (achievements, actions, etc.)
  NotificationSoundName, // Notification sounds (alerts, success, etc.)
  AudioPermissionStatus  // 'granted' | 'prompt' | 'unavailable'
} from 'react-sounds';
import customSound from '../assets/sounds/custom.mp3';

// Using with type safety
function PlaySounds() {
  // For built-in sounds, use the type for type checking
  const playUiSound = (sound: UiSoundName) => playSound(sound);
  
  // For custom sounds, just import and use directly
  const playCustomSound = () => playSound(customSound);
  
  return (
    <div>
      <button onClick={() => playUiSound('ui/button_soft')}>UI Sound</button>
      <button onClick={playCustomSound}>Custom Sound</button>
    </div>
  );
}

Sound Hook Return Type

Type definition for what useSound hook returns.

import type { SoundHookReturn } from 'react-sounds';

// SoundHookReturn contains:
// {
//   play: (options?: SoundOptions) => Promise<void> | undefined;
//   stop: () => void;
//   pause: () => void;
//   resume: () => void;
//   isPlaying: boolean;
//   isLoaded: boolean;
//   checkPermission: () => Promise<AudioPermissionStatus>;
// }