Skip to main content
The useVoiceVisualizer hook provides comprehensive controls and state management for audio recording and visualization. It handles microphone access, audio recording, playback, and provides formatted time values for display.

Import

import { useVoiceVisualizer } from "react-voice-visualizer";

Basic Usage

import { useVoiceVisualizer } from "react-voice-visualizer";

function AudioRecorder() {
  const recorderControls = useVoiceVisualizer({
    onStartRecording: () => console.log("Recording started"),
    onStopRecording: () => console.log("Recording stopped"),
  });

  return <VoiceVisualizer controls={recorderControls} />;
}

Parameters

All parameters are optional and can be passed as an object to the hook.
onStartRecording
() => void
Callback function triggered when recording starts.
onStopRecording
() => void
Callback function triggered when recording stops.
onPausedRecording
() => void
Callback function triggered when recording is paused.
onResumedRecording
() => void
Callback function triggered when recording is resumed.
onClearCanvas
() => void
Callback function triggered when the canvas is cleared.
onEndAudioPlayback
() => void
Callback function triggered when audio playback ends.
onStartAudioPlayback
() => void
Callback function triggered when audio playback starts.
onPausedAudioPlayback
() => void
Callback function triggered when audio playback is paused.
onResumedAudioPlayback
() => void
Callback function triggered when audio playback is resumed.
onErrorPlayingAudio
(error: Error) => void
Callback function invoked when an error occurs during the execution of audio.play(). It provides an opportunity to handle and respond to such errors.
shouldHandleBeforeUnload
boolean
default:"true"
Determines whether the beforeunload event handler should be added to the window, preventing page unload if necessary.

Return Values

The hook returns a Controls object containing state values, functions, refs, and formatted values.

State Values

isRecordingInProgress
boolean
Indicates if audio recording is currently in progress.
isPausedRecording
boolean
Indicates if audio recording is currently paused.
audioData
Uint8Array
Audio data for real-time visualization during recording.
recordingTime
number
Elapsed time during recording in milliseconds.
duration
number
Duration of the recorded audio in seconds.
currentAudioTime
number
Current playback time of the recorded audio in seconds.
audioSrc
string
Source URL of the recorded audio file for playback.
isPausedRecordedAudio
boolean
Indicates if recorded audio playback is paused.
isProcessingRecordedAudio
boolean
Indicates if the recorded audio is being processed and ‘Processing Audio…’ text is shown.
isCleared
boolean
Indicates if the canvas has been cleared.
isAvailableRecordedAudio
boolean
Indicates whether recorded audio is available and not currently being processed. This return value can be used to check if it’s an appropriate time to work with recorded audio data in your application.
recordedBlob
Blob | null
Recorded audio data in Blob format.
bufferFromRecordedBlob
AudioBuffer | null
Audio buffer from the recorded Blob.
error
Error | null
Error object if any error occurred during recording or playback.
isProcessingOnResize
boolean
Indicates whether audio processing is occurring during a resize event when audio is recorded and a blob is present.
isProcessingStartRecording
boolean
When set to true, it indicates that the start recording button has been pressed, but either the permission to record has not yet been granted or the recording itself has not yet commenced. This prop serves as a helpful flag to manage the state of the recording process, allowing components to react accordingly to the current stage of recording initiation.
isPreloadedBlob
boolean
This property indicates whether a preloaded audio blob is available for playback or processing.
mediaRecorder
MediaRecorder | null
MediaRecorder instance used for recording audio.

Formatted Values

formattedDuration
string
Formatted duration time in format 09:51m.
formattedRecordingTime
string
Formatted recording current time in format 09:51.
formattedRecordedAudioCurrentTime
string
Formatted recorded audio current time in format 09:51:1.

Functions

startRecording
() => void
Function to start audio recording. Requests microphone permission if not already granted.
stopRecording
() => void
Function to stop audio recording.
togglePauseResume
() => void
Function to toggle pause/resume during recording and playback of recorded audio.
startAudioPlayback
() => void
Function to start/resume playback of recorded audio.
stopAudioPlayback
() => void
Function to pause playback of recorded audio.
saveAudioFile
() => void
This function allows you to save the recorded audio as a webm file format. Please note that it supports saving audio only in the webm format. If you need to save the audio in a different format, you can use external libraries like FFmpeg to convert the Blob to your desired format. This flexibility allows you to tailor the output format according to your specific needs.
clearCanvas
() => void
Function to clear the visualization canvas and reset all states.
setCurrentAudioTime
Dispatch<SetStateAction<number>>
Internal function to handle current audio time updates during playback.
setPreloadedAudioBlob
(blob: Blob) => void
Users can use this method to set a preloaded audio blob, enabling seamless integration with user inputs, file uploads, etc.

Refs

audioRef
MutableRefObject<HTMLAudioElement | null>
Reference to the audio element used for playback.

Internal Functions

Functions prefixed with _ are internal and should not be used directly in most cases.
_setIsProcessingAudioOnComplete
Dispatch<SetStateAction<boolean>>
Internal function to set isProcessingAudioOnComplete state.
_setIsProcessingOnResize
Dispatch<SetStateAction<boolean>>
Internal function to set isProcessingOnResize state.

Examples

Callback Lifecycle

import { useVoiceVisualizer } from "react-voice-visualizer";

function AudioRecorder() {
  const recorderControls = useVoiceVisualizer({
    onStartRecording: () => {
      console.log("Recording started");
      // Update UI, send analytics, etc.
    },
    onPausedRecording: () => {
      console.log("Recording paused");
    },
    onResumedRecording: () => {
      console.log("Recording resumed");
    },
    onStopRecording: () => {
      console.log("Recording stopped");
      // Process the recorded blob
    },
    onStartAudioPlayback: () => {
      console.log("Playback started");
    },
    onPausedAudioPlayback: () => {
      console.log("Playback paused");
    },
    onResumedAudioPlayback: () => {
      console.log("Playback resumed");
    },
    onEndAudioPlayback: () => {
      console.log("Playback ended");
    },
    onErrorPlayingAudio: (error) => {
      console.error("Audio playback error:", error);
      // Show error to user
    },
  });

  return <VoiceVisualizer controls={recorderControls} />;
}

Custom Controls

import { useVoiceVisualizer } from "react-voice-visualizer";

function CustomAudioRecorder() {
  const recorderControls = useVoiceVisualizer();

  return (
    <div>
      <VoiceVisualizer 
        controls={recorderControls} 
        isControlPanelShown={false}
      />
      
      {/* Custom control buttons */}
      <button 
        onClick={recorderControls.startRecording}
        disabled={recorderControls.isRecordingInProgress}
      >
        Start Recording
      </button>
      
      <button 
        onClick={recorderControls.togglePauseResume}
        disabled={!recorderControls.isRecordingInProgress}
      >
        {recorderControls.isPausedRecording ? "Resume" : "Pause"}
      </button>
      
      <button 
        onClick={recorderControls.stopRecording}
        disabled={!recorderControls.isRecordingInProgress}
      >
        Stop Recording
      </button>
      
      <button 
        onClick={recorderControls.clearCanvas}
        disabled={recorderControls.isCleared}
      >
        Clear
      </button>
      
      {recorderControls.isRecordingInProgress && (
        <p>Recording: {recorderControls.formattedRecordingTime}</p>
      )}
      
      {recorderControls.isAvailableRecordedAudio && (
        <p>Duration: {recorderControls.formattedDuration}</p>
      )}
    </div>
  );
}

Preloading Audio

import { useVoiceVisualizer } from "react-voice-visualizer";
import { useEffect } from "react";

function PreloadedAudio({ audioBlob }: { audioBlob: Blob }) {
  const recorderControls = useVoiceVisualizer();

  useEffect(() => {
    if (audioBlob) {
      recorderControls.setPreloadedAudioBlob(audioBlob);
    }
  }, [audioBlob]);

  return (
    <div>
      <VoiceVisualizer controls={recorderControls} />
      
      {recorderControls.isPreloadedBlob && (
        <p>Preloaded audio ready for playback</p>
      )}
    </div>
  );
}
For a complete list of TypeScript types, see the Types reference.

See Also

Build docs developers (and LLMs) love