react-voice-visualizer

repository·main·Indexed 42 days ago

https://github.com/yzarytskyi/react-voice-visualizer

A React library for capturing, visualizing, and manipulating audio recordings using the Web Audio API. Version 2.1.0 provides the useVoiceVisualizer hook for recording management and the VoiceVisualizer component for rendering real-time audio waveforms.

Tokens
5.4K
Snippets
9
Records
11
Agent score
52%

What's inside react-voice-visualizer

  1. Quickstart: Use the VoiceVisualizer component and useVoiceVisualizer hook

    main

    To implement audio recording and visualization, follow these steps:

    1. Import useVoiceVisualizer and VoiceVisualizer from react-voice-visualizer.
    2. Initialize the recorder controls by calling useVoiceVisualizer().
    3. Pass the returned recorderControls object to the VoiceVisualizer component via the controls prop.
    4. Access states like recordedBlob or error from the hook to handle the recording lifecycle.

    Note: In version 2.x.x, audio references (audioRef) are managed internally; you no longer need to pass a ref to the component manually.

    import { useEffect } from "react";
    import { useVoiceVisualizer, VoiceVisualizer } from "react-voice-visualizer";
    
    const App = () => {
        // Initialize the recorder controls using the hook
        const recorderControls = useVoiceVisualizer();
        const {
            // ... (Extracted controls and states, if necessary)
            recordedBlob,
            error,
        } = recorderControls;
    
        // Get the recorded audio blob
        useEffect(() => {
            if (!recordedBlob) return;
    
            console.log(recordedBlob);
        }, [recordedBlob]);
    
        // Get the error when it occurs
        useEffect(() => {
            if (!error) return;
    
            console.error(error);
        }, [error]);
    
        return (
            <VoiceVisualizer controls={recorderControls} />
        );
    };
    
    export default App;
  2. Use the `VoiceVisualizer` component

    main

    The VoiceVisualizer component renders the actual visual waveform. It requires a controls prop, which is the object returned by the useVoiceVisualizer() hook. You can customize the appearance (colors, width, height, speed) and control whether the default UI (buttons, progress indicators) is shown.

    // Example conceptual usage
    const controls = useVoiceVisualizer();
    
    return (
      <VoiceVisualizer 
        controls={controls} 
        height={300} 
        mainBarColor="#ff0000" 
      />
    );
  3. Use the `useVoiceVisualizer()` hook

    main

    The useVoiceVisualizer() hook is the core engine of the library. It provides the state and control functions necessary to manage audio recording, playback, and real-time visualization data. You can pass optional callback functions to handle lifecycle events like recording start/stop, playback start/stop, or errors.

    const recorderControls = useVoiceVisualizer();
  4. Reference `useVoiceVisualizer()` hook parameters

    main

    The useVoiceVisualizer() hook accepts an optional configuration object. Use these parameters to hook into the recording and playback lifecycle or to configure the underlying MediaRecorder.

    | Parameter | Type | Description |
    |:---|:---|:---|
    | `onStartRecording` | `() => void` | Callback triggered when recording starts. |
    | `onStopRecording` | `() => void` | Callback triggered when recording stops. |
    | `onPausedRecording` | `() => void` | Callback triggered when recording is paused. |
    | `onResumedRecording` | `() => void` | Callback triggered when recording is resumed. |
    | `onClearCanvas` | `() => void` | Callback triggered when the canvas is cleared. |
    | `onEndAudioPlayback` | `() => void` | Callback triggered when audio playback ends. |
    | `onStartAudioPlayback` | `() => void` | Callback triggered when audio playback starts. |
    | `onPausedAudioPlayback` | `() => void` | Callback triggered when audio playback is paused. |
    | `onResumedAudioPlayback` | `() => void` | Callback triggered when audio playback is resumed. |
    | `onErrorPlayingAudio` | `(error: Error) => void` | Invoked when an error occurs during `audio.play()`. |
    | `shouldHandleBeforeUnload` | `boolean` | Prevents page unload if `true` (default). |
    | `mediaRecorderOptions` | `MediaRecorderOptions` | Configuration for the MediaRecorder instance. |
  5. Reference `useVoiceVisualizer()` hook return values

    main

    The useVoiceVisualizer() hook returns an object containing state variables, formatted strings, and control functions. These are used to drive both the UI and the logic of your application.

    | Returns | Type | Description |
    |:---|:---|:---|
    | `audioRef` | `MutableRefObject<HTMLAudioElement | null>` | Reference to the audio element used for playback. |
    | `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. |
    | `recordingTime` | `number` | Elapsed time during recording in milliseconds. |
    | `mediaRecorder` | `MediaRecorder | null` | MediaRecorder instance used for recording audio. |
    | `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 recorded audio is being processed. |
    | `isCleared` | `boolean` | Indicates if the canvas has been cleared. |
    | `isAvailableRecordedAudio` | `boolean` | Indicates if recorded audio is available and not being processed. |
    | `recordedBlob` | `Blob | null` | Recorded audio data in Blob format. |
    | `bufferFromRecordedBlob` | `AudioBuffer | null` | Audio buffer from the recorded Blob. |
    | `formattedDuration` | `string` | Formatted duration (e.g., 09:51m). |
    | `formattedRecordingTime` | `string` | Formatted recording time (e.g., 09:51). |
    | `formattedRecordedAudioCurrentTime` | `string` | Formatted playback time (e.g., 09:51:1). |
    | `startRecording` | `() => void` | Function to start audio recording. |
    | `togglePauseResume` | `() => void` | Toggles pause/resume during recording and playback. |
    | `startAudioPlayback` | `() => void` | Starts/resumes playback of recorded audio. |
    | `stopAudioPlayback` | `() => void` | Pauses playback of recorded audio. |
    | `stopRecording` | `() => void` | Stops audio recording. |
    | `saveAudioFile` | `() => void` | Saves recorded audio as a `webm` file. |
    | `clearCanvas` | `() => void` | Clears the visualization canvas. |
    | `setCurrentAudioTime` | `Dispatch<SetStateAction<number>>` | Internal function for audio time updates. |
    | `error` | `Error | null` | Error object if recording/playback fails. |
    | `isProcessingOnResize` | `boolean` | Indicates audio processing during resize. |
    | `isProcessingStartRecording` | `boolean` | Indicates if recording is initiating (waiting for permissions). |
    | `isPreloadedBlob` | `boolean` | Indicates if a preloaded audio blob is available. |
    | `setPreloadedAudioBlob` | `(blob: Blob) => void` | Sets a preloaded audio blob (e.g., from file upload). |
  6. Reference `VoiceVisualizer` component props

    main

    Configure the visual appearance and UI behavior of the VoiceVisualizer component using these props.

    | Props | Description | Default | Type |
    |:---|:---|:---|:---|
    | `controls` | Audio recording controls and states | - | `Controls` (Required) |
    | `height` | Height of the visualization canvas | `200` | `string | number` |
    | `width` | Width of the visualization canvas | `100%` | `string | number` |
    | `backgroundColor` | Background color of the canvas | `transparent` | `string` |
    | `mainBarColor` | Color of the main audio wave line | `#FFFFFF` | `string` |
    | `secondaryBarColor` | Color of the secondary audio wave line | `#5e5e5e` | `string` |
    | `speed` | Animation speed (1-6, higher is slower) | `3` | `number` |
    | `barWidth` | Width of each audio wave bar | `2` | `number` |
    | `gap` | Gap between each audio wave bar | `1` | `number` |
    | `rounded` | Border radius of the audio wave bars | `5` | `number` |
    | `isControlPanelShown` | Whether to display the default control panel | `true` | `boolean` |
    | `isDownloadAudioButtonShown` | Whether to display the Download button | `false` | `boolean` |
    | `fullscreen` | Whether to display in fullscreen mode | `false` | `boolean` |
    | `animateCurrentPick` | Whether to animate the current pick | `true` | `boolean` |
    | `onlyRecording` | Show visualization only during recording | `false` | `boolean` |
    | `isDefaultUIShown` | Show default UI on Canvas before recording | `true` | `boolean` |
    | `mainContainerClassName` | CSS class for the main container | - | `string` |
    | `canvasContainerClassName` | CSS class for the canvas container | - | `string` |
    | `isProgressIndicatorShown` | Show progress indicator after recording | `true` | `boolean` |
    | `progressIndicatorClassName` | CSS class for progress indicator | - | `string` |
    | `isProgressIndicatorTimeShown` | Show progress indicator time | `true` | `boolean` |
    | `isProgressIndicatorTimeClassName` | CSS class for progress indicator time | - | `string` |
    | `isProgressIndicatorOnHoverShown` | Show progress indicator on hover | `true` | `boolean` |
    | `progressIndicatorOnHoverClassName` | CSS class for hover progress indicator | - | `string` |
    | `isProgressIndicatorTimeOnHoverShown` | Show progress indicator time on hover | `true` | `boolean` |
    | `progressIndicatorTimeOnHoverClassName` | CSS class for hover progress indicator time | - | `string` |
    | `isAudioProcessingTextShown` | Show audio processing text | `true` | `boolean` |
    | `audioProcessingTextClassName` | CSS class for audio processing text | - | `string` |
    | `controlButtonsClassName` | CSS class for Clear and Download buttons | - | `string` |
  7. Version 2.x.x Breaking Changes and New Features

    main

    Breaking Changes

    • Ref Handling Update: The library now manages audioRef internally. You do not need to pass ref={audioRef} to components anymore.

    New Features

    • Preloaded Audio Blob Support: You can now load existing audio blobs (from user inputs or files) using the setPreloadedAudioBlob function.
  8. Configure the useVoiceVisualizer hook

    main

    When using the useVoiceVisualizer hook, you can provide an optional useVoiceVisualizerParams object to handle lifecycle events and configure the MediaRecorder.

    Available callback props:

    • onStartRecording?: Triggered when recording begins.
    • onStopRecording?: Triggered when recording stops.
    • onPausedRecording?: Triggered when recording is paused.
    • onResumedRecording?: Triggered when recording resumes.
    • onClearCanvas?: Triggered when the canvas is cleared.
    • onEndAudioPlayback?: Triggered when audio playback finishes.
    • onStartAudioPlayback?: Triggered when audio playback starts.
    • onPausedAudioPlayback?: Triggered when audio playback is paused.
    • onResumedAudioPlayback?: Triggered when audio playback resumes.
    • onErrorPlayingAudio?: Triggered with an Error if audio playback fails.
    • onChunkAvailable?: Triggered with a Blob chunk when timeslice is used.
    • onClearCanvas?: Triggered when the canvas is cleared.

    Configuration props:

    • mediaRecorderOptions?: Standard MediaRecorderOptions for the recording engine.
    • timeslice?: A number representing the interval (in ms) at which data chunks are emitted via onChunkAvailable.
    • shouldHandleBeforeUnload?: Boolean to determine if the hook should handle browser unload events.
    const { ... } = useVoiceVisualizer({
      onStartRecording: () => console.log('Started!'),
      onStopRecording: () => console.log('Stopped!'),
      mediaRecorderOptions: { mimeType: 'audio/webm' },
      timeslice: 1000,
      onChunkAvailable: (chunk) => console.log('New chunk:', chunk),
    });
  9. Understand the Controls object structure

    main

    The Controls interface provides the state and methods returned by the visualizer to manage recording and playback.

    State Properties:

    • audioRef: A MutableRefObject pointing to the HTMLAudioElement.
    • isRecordingInProgress: Boolean indicating if a recording is active.
    • isPausedRecording: Boolean indicating if the recording is currently paused.
    • audioData: The raw Uint8Array audio data.
    • recordingTime: Current elapsed recording time (number).
    • duration: Total duration of the audio.
    • currentAudioTime: Current playback position (number).
    • audioSrc: The source URL for the audio.
    • isPausedRecordedAudio: Boolean indicating if playback is paused.
    • isProcessingRecordedAudio: Boolean indicating if the recorded audio is being processed.
    • isCleared: Boolean indicating if the canvas/data has been cleared.
    • isAvailableRecordedAudio: Boolean indicating if recorded audio is ready.
    • recordedBlob: The Blob containing the recorded audio.
    • bufferFromRecordedBlob: The AudioBuffer parsed from the blob.
    • formattedDuration: Human-readable duration string.
    • formattedRecordingTime: Human-readable recording time string.
    • formattedRecordedAudioCurrentTime: Human-readable playback time string.
    • error: Any Error encountered during operation.
    • isProcessingOnResize: Boolean indicating if processing is happening due to a resize event.
    • isProcessingStartRecording: Boolean indicating if processing is happening at the start of recording.
    • isPreloadedBlob: Boolean indicating if a blob was preloaded.

    Action Methods:

    • startRecording(): Begins the recording process.
    • stopRecording(): Ends the recording process.
    • togglePauseResume(): Toggles pause/resume state for recording.
    • startAudioPlayback(): Starts playing the recorded audio.
    • stopAudioPlayback(): Stops audio playback.
    • saveAudioFile(): Triggers a download of the audio file.
    • clearCanvas(): Clears the visualizer canvas.
    • setCurrentAudioTime(value): Updates the current audio playback time.
    • setPreloadedAudioBlob(blob): Sets a preloaded audio blob.
    • _setIsProcessingAudioOnComplete(boolean): Internal state setter for audio processing completion.
    • _setIsProcessingOnResize(boolean): Internal state setter for resize processing.