Rooks

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://commondatastorage.googleapis.com/codeskulptor-demos/DDR_assets/Sevish_-__nbsp_.mp3";
  const [audioRef, audioState, audioControls] = useAudio({
    autoPlay: false,
  });
 
  return (
    <>
      {audioState.isPlaying ? "Playing" : "Not playing "}
      <br />
      <audio ref={audioRef} src={audioSrc} />
      <button onClick={audioControls.play}>Play</button>
      <button onClick={audioControls.pause}>Pause</button>
      <button onClick={audioControls.toggleMute}>
        {audioState.isMuted ? "Unmute" : "Mute"}
      </button>
    </>
  );
}

Arguments

Argument valueTypeDescriptionDefault
optionsObjectSee table below
callbacksObjectSee table below

Options

Options valueTypeDescriptionDefault
autoPlayBooleanIndicates if the audio should start playing automaticallyfalse
isMutedBooleanIndicates if the audio should be muted by defaultfalse

Callbacks

Callbacks valueTypeDescriptionDefault
onPlayFunctionCalled when audio starts playingundefined
onPauseFunctionCalled when audio is pausedundefined
onMuteFunctionCalled when audio is mutedundefined
onUnmuteFunctionCalled when audio is unmutedundefined
onLoadedMetadataFunctionCalled when audio metadata is loadedundefined

Returns

Returns an array with three elements:

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

State Properties

PropertyTypeDescription
isPlayingBooleanWhether the audio is playing
isMutedBooleanWhether the audio is muted

Control Methods

MethodTypeDescription
playFunctionStart playing the audio
pauseFunctionPause the audio
togglePlayFunctionToggle play/pause state
muteFunctionMute the audio
unmuteFunctionUnmute the audio
toggleMuteFunctionToggle mute/unmute state

On this page