### Install use-sound with Yarn or NPM Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Instructions for adding the use-sound package to your project using either Yarn or NPM package managers. It also mentions the availability of a UMD build and the need to install @types/howler for TypeScript projects. ```bash yarn add use-sound ``` ```bash npm install use-sound ``` -------------------------------- ### Play Sound on Click with use-sound Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Example of how to play a sound effect when a button is clicked using the use-sound hook. It demonstrates importing the hook and the sound file, and then calling the returned play function on click. ```javascript import useSound from 'use-sound'; import boopSfx from '../../sounds/boop.mp3'; const BoopButton = () => { const [play] = useSound(boopSfx); return ; }; ``` -------------------------------- ### Playing a Sound with use-sound Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md This snippet demonstrates the basic usage of the use-sound hook to play an audio file. It shows how to get the play function from the hook and call it. ```javascript const [play] = useSound('/meow.mp3'); // To play the sound: // play(); ``` -------------------------------- ### Control Audio with Howler.js 'sound' Object: Fade Example Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Access the Howler.js 'sound' object directly from useSound to utilize advanced Howler methods. This example demonstrates fading an audio file in using the 'fade' method. Requires the 'sound' object to be destructured from the hook. ```javascript const Arcade = () => { const [play, { sound }] = useSound('/win-theme.mp3'); return ( ); }; ``` -------------------------------- ### Pause and Resume Functionality with useSound Source: https://context7.com/joshwcomeau/use-sound/llms.txt Provides an example of implementing pause and resume functionality for audio playback. It uses the 'pause' function and retrieves the audio 'duration' from the useSound hook's return values. ```jsx import useSound from 'use-sound'; import musicSfx from './sounds/music.mp3'; const MusicPlayer = () => { const [play, { pause, duration, sound }] = useSound(musicSfx); return (

Duration: {duration ? `${duration}ms` : 'Loading...'}

); }; ``` -------------------------------- ### Delegate Unrecognized Options to Howler.js Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Pass unrecognized options to useSound hook, which are then delegated to Howler.js. This allows for advanced configurations like event callbacks. Example uses 'onend' to log a message when audio finishes. ```javascript const [play] = useSound('/thing.mp3', { onend: () => { console.info('Sound ended!'); }, }); ``` -------------------------------- ### Runtime Playback Rate Adjustment with useSound (React) Source: https://context7.com/joshwcomeau/use-sound/llms.txt This example showcases how to dynamically adjust the playback rate of a sound effect at runtime using the `playbackRate` option within the useSound hook. It allows for interactive control over the speed of audio playback, enabling effects like slow-motion or speed-up sounds based on user input. ```jsx import useSound from 'use-sound'; import bounceSfx from './sounds/bounce.mp3'; const BounceButton = () => { const [play] = useSound(bounceSfx); const handleSlow = () => play({ playbackRate: 0.5 }); const handleNormal = () => play({ playbackRate: 1.0 }); const handleFast = () => play({ playbackRate: 2.0 }); return (
); }; ``` -------------------------------- ### Increase Pitch on Click with use-sound Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md An example showing how to dynamically change the playback rate (and thus pitch) of a sound effect with each click. It uses React's useState to manage the playback rate and passes it to the useSound hook along with the `interrupt: true` option. ```javascript import useSound from 'use-sound'; import glugSfx from '../../sounds/glug.mp3'; export const RisingPitch = () => { const [playbackRate, setPlaybackRate] = React.useState(0.75); const [play] = useSound(glugSfx, { playbackRate, // `interrupt` ensures that if the sound starts again before it's // ended, it will truncate it. Otherwise, the sound can overlap. interrupt: true, }); const handleClick = () => { setPlaybackRate(playbackRate + 0.1); play(); }; return ( ); }; ``` -------------------------------- ### use-sound Play Function Options Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Illustrates how to call the play function with options to control playback, such as ID for sprites, forceSoundEnabled, and playbackRate. ```javascript const [play] = useSound('/meow.mp3'); // Example with options: play({ id: 'laser', forceSoundEnabled: true, playbackRate: 1.5 }); ``` -------------------------------- ### Configuring Audio Sprites with use-sound Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Demonstrates how to define and use audio sprites with the use-sound hook. This involves creating a sprite map and passing it as an option to the hook. ```javascript const spriteMap = { laser: [0, 300], explosion: [1000, 300], meow: [2000, 75], }; const [play] = useSound('/path/to/sprite.mp3', { sprite: spriteMap }); // To play a specific sprite: // play({ id: 'laser' }); ``` -------------------------------- ### useSound Hook Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md The useSound hook takes a URL to a sound file and an optional configuration object. It returns a play function and an object with playback data and controls. ```APIDOC ## useSound Hook ### Description The `useSound` hook is designed to handle audio playback in React applications. It accepts a URL to an audio file and an optional configuration object (`HookOptions`). It returns a tuple containing a function to trigger the sound playback and an object (`ExposedData`) with additional data and controls. ### Arguments 1. **`url`** (string): The path to the audio file to be loaded. 2. **`options`** (HookOptions): An optional object containing configuration for the sound playback. ### Returns A tuple `[play, exposedData]`: - **`play`** (function): A function to trigger the sound playback. Can optionally accept `PlayOptions`. - **`exposedData`** (object): An object containing playback data and controls. ### HookOptions Configuration options for the `useSound` hook. | Name | Type | Description | |---------------|-------------------|------------------------------------------------------------------------------------------------------------| | `volume` | number (0 to 1) | Sets the volume of the sound. `1` is full volume, `0` is muted. | | `playbackRate`| number (0.5 to 4) | Controls the playback speed. Affects pitch similarly to a turntable. Reactive by default, unless `sprite` is used. | | `interrupt` | boolean | If true, allows a new sound to start before the previous one finishes. | | `soundEnabled`| boolean | Global mute switch. If false, no sounds will play. Can be overridden by `PlayOptions`. | | `sprite` | SpriteMap | Allows multiple sound effects from a single `useSound` hook. See "Sprites" documentation. | | `[delegated]` | any | Additional arguments are forwarded to the Howl constructor. See "Escape hatches" documentation. | **Note**: If `sprite` is provided, `playbackRate` will not be reactive and only the initial value will be used. ### PlayOptions Options that can be passed when calling the `play` function to override `HookOptions` for a specific playback instance. - **`id`** (string): If using sprites, specify which sound effect to play. - **`forceSoundEnabled`** (boolean): Overrides the global `soundEnabled` setting for this specific playback. ### Request Example (Hook Usage) ```javascript import React from 'react'; import useSound from 'use-sound'; const soundFile = '/path/to/your/sound.mp3'; function MyComponent() { const [play, { pause, stop, isPlaying, duration, sound }] = useSound(soundFile, { playbackRate: 0.75, volume: 0.5, interrupt: true, soundEnabled: true }); return (
{isPlaying &&

Sound is playing...

}
); } ``` ### Response Example (ExposedData) ```json { "isPlaying": true, "isPaused": false, "duration": 12345, "volume": 0.5, "playbackRate": 0.75, "sound": { /* Howl object */ } } ``` ``` -------------------------------- ### Importing Audio Files in Create React App Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Demonstrates how to import an audio file (e.g., MP3) in a Create React App project. The import resolves to a dynamically generated path that can be used by `use-sound`. This method is specific to bundlers like Webpack configured for Create React App. ```javascript import someAudioFile from '../sounds/sound.mp3'; console.log(someAudioFile); // “/build/sounds/sound-abc123.mp3” ``` -------------------------------- ### Basic Sound Playback on Click with useSound Source: https://context7.com/joshwcomeau/use-sound/llms.txt Demonstrates how to play a sound effect when a button is clicked using the useSound hook. It imports the hook and the sound file, then uses the returned play function in an onClick handler. ```jsx import useSound from 'use-sound'; import boopSfx from './sounds/boop.mp3'; const BoopButton = () => { const [play] = useSound(boopSfx); return ; }; ``` -------------------------------- ### Accessing use-sound Exposed Data Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Shows how to access additional data and functions provided by the use-sound hook, including stop, pause, duration, and the raw sound object. ```javascript const [play, exposedData] = useSound('/meow.mp3'); // Accessing exposed data: // exposedData.stop(); // exposedData.pause(); // const duration = exposedData.duration; // const sound = exposedData.sound; ``` -------------------------------- ### Play Sound on Hover with use-sound Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Demonstrates playing a sound effect when hovering over an element and stopping it when the mouse leaves. It utilizes the play and stop functions returned by useSound. Note that browser policies may require user interaction before sounds can play. ```javascript import useSound from 'use-sound'; import fanfareSfx from '../../sounds/fanfare.mp3'; const FanfareButton = () => { const [play, { stop }] = useSound(fanfareSfx); return ( ); }; ``` -------------------------------- ### Audio Sprites for Multiple Sounds with useSound Source: https://context7.com/joshwcomeau/use-sound/llms.txt Demonstrates the use of audio sprites to manage and play multiple sound segments from a single audio file. The 'sprite' option in useSound is configured with time ranges for each sound, allowing playback by ID. ```jsx import useSound from 'use-sound'; import drumSfx from './sounds/909-drums.mp3'; const DrumMachine = () => { const [play] = useSound(drumSfx, { sprite: { kick: [0, 350], hihat: [374, 160], snare: [666, 290], cowbell: [968, 200], }, }); return (
); }; ``` -------------------------------- ### Reactive Playback Rate Configuration in use-sound Source: https://github.com/joshwcomeau/use-sound/blob/main/README.md Illustrates how the `useSound` hook in React allows for reactive configuration. Changes to options like `playbackRate` passed during hook invocation will immediately affect the sound's playback without needing to re-initialize the hook. This behavior applies to all options passed in `HookOptions`. ```javascript const [playbackRate, setPlaybackRate] = React.useState(0.75); const [play] = useSound('/path/to/sound', { playbackRate }); ``` -------------------------------- ### Dynamic Playback Rate Control with useSound Source: https://context7.com/joshwcomeau/use-sound/llms.txt Illustrates how to dynamically change the playback rate of a sound effect based on user interaction. It uses React's useState hook to manage the playback rate and passes it as a configuration option to useSound. ```jsx import React from 'react'; import useSound from 'use-sound'; import glugSfx from './sounds/glug.mp3'; const RisingPitch = () => { const [playbackRate, setPlaybackRate] = React.useState(0.75); const [play] = useSound(glugSfx, { playbackRate, volume: 0.5, interrupt: true, }); const handleClick = () => { setPlaybackRate(playbackRate + 0.1); play(); }; return ; }; ``` -------------------------------- ### Play and Stop Sound on Hover with useSound Source: https://context7.com/joshwcomeau/use-sound/llms.txt Shows how to play a sound when the mouse hovers over a button and stop it when the mouse leaves. It utilizes the 'play' and 'stop' functions returned by useSound, along with onMouseEnter and onMouseLeave event handlers. ```jsx import useSound from 'use-sound'; import fanfareSfx from './sounds/fanfare.mp3'; const FanfareButton = () => { const [play, { stop }] = useSound(fanfareSfx, { volume: 0.5 }); return ( ); }; ``` -------------------------------- ### Advanced Howler.js Integration with Fade using useSound Source: https://context7.com/joshwcomeau/use-sound/llms.txt Demonstrates advanced integration with Howler.js via useSound, specifically using the 'sound' object to control fading. It plays a sound and then fades its volume from 0 to 1 over 2 seconds. ```jsx import useSound from 'use-sound'; import victorySfx from './sounds/victory.mp3'; const VictoryButton = () => { const [play, { sound }] = useSound(victorySfx, { volume: 0, onend: () => { console.log('Victory theme finished!'); }, }); const handleWin = () => { if (sound) { play(); sound.fade(0, 1, 2000); // Fade from 0 to 1 over 2 seconds } }; return ; }; ``` -------------------------------- ### Multiple Independent Sound Instances with useSound (React) Source: https://context7.com/joshwcomeau/use-sound/llms.txt This snippet shows how to manage multiple independent sound instances using the useSound hook. Each sound is imported and played based on user interaction, allowing for distinct audio feedback for different states or actions. It utilizes React's useState hook to manage component state. ```jsx import useSound from 'use-sound'; import popDown from './sounds/pop-down.mp3'; import popUpOn from './sounds/pop-up-on.mp3'; import popUpOff from './sounds/pop-up-off.mp3'; const Checkbox = () => { const [isChecked, setIsChecked] = React.useState(false); const [playActive] = useSound(popDown, { volume: 0.25 }); const [playOn] = useSound(popUpOn, { volume: 0.25 }); const [playOff] = useSound(popUpOff, { volume: 0.25 }); return ( setIsChecked(!isChecked)} onMouseDown={playActive} onMouseUp={() => (isChecked ? playOff() : playOn())} /> ); }; ``` -------------------------------- ### Global Sound Enable/Disable Toggle with useSound Source: https://context7.com/joshwcomeau/use-sound/llms.txt Shows how to implement a global mute/unmute toggle for sound effects. The 'soundEnabled' prop is passed to the useSound hook, controlling whether sounds can play. ```jsx import React from 'react'; import useSound from 'use-sound'; import clickSfx from './sounds/click.mp3'; const App = () => { const [soundEnabled, setSoundEnabled] = React.useState(true); return (
); }; const ActionButton = ({ soundEnabled }) => { const [play] = useSound(clickSfx, { soundEnabled }); return ; }; ``` -------------------------------- ### Force Sound Playback Override with useSound (React) Source: https://context7.com/joshwcomeau/use-sound/llms.txt Demonstrates how to force a sound to play even when global sound is disabled, using the `forceSoundEnabled` option in useSound. This is useful for critical audio cues or user-initiated actions where sound feedback is essential regardless of global settings. The `soundEnabled` prop on useSound controls the default behavior. ```jsx import useSound from 'use-sound'; import muteSfx from './sounds/mute.mp3'; const MuteButton = ({ soundEnabled }) => { const [play] = useSound(muteSfx, { soundEnabled }); // Force sound to play even when globally muted const handleClick = () => { play({ forceSoundEnabled: true }); }; return ; }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.