useAudio

About

A hook to control and manage audio elements in your React application.

Examples

Basic example

import { useAudio } from "rooks";

export default function App() {
  const audioSrc = "https://example.com/audio.mp3";
  const [{ isPlaying, isMuted }, audioRef] = useAudio({ autoPlay: false });

  const handlePlay = () => audioRef.current.play();
  const handlePause = () => audioRef.current.pause();
  const handleToggleMute = () => (audioRef.current.muted = !isMuted);

  return (
    <>
      <audio ref={audioRef} src={audioSrc} />
      <button onClick={handlePlay}>Play</button>
      <button onClick={handlePause}>Pause</button>
      <button onClick={handleToggleMute}>{isMuted ? "Unmute" : "Mute"}</button>
    </>
  );
}

Arguments

Argument valueTypeDescriptionDefault
optionsObjectSee table below
Options valueTypeDescriptionDefault
autoPlayBooleanIndicates if the audio should start playing automaticallyfalse
isMutedBooleanIndicates if the audio should be muted by defaultfalse

Returns

Return valueTypeDescriptionDefault
stateObjectAn object containing isPlaying and isMuted properties
refCallback RefA ref that should be used on the audio element you want to controlundefined

Join the community!

Join our discord server! You can click the floating discord icon at the bottom right of the screen and chat with us!

Powered by vercel