Basic Usage
Getting Started
The react-audio-recorder-hook
provides a simple interface for recording audio in your React applications. Here’s a basic example showing how to use the hook:
import React from 'react';import { useReactAudioRecorder } from 'react-audio-recorder-hook';
function AudioRecorder() { const { startRecording, stopRecording, audioResult, status, errorMessage } = useReactAudioRecorder();
return ( <div> <button onClick={startRecording} disabled={status === 'recording'} > Start Recording </button>
<button onClick={stopRecording} disabled={status !== 'recording'} > Stop Recording </button>
{status === 'recording' && <p>Recording in progress...</p>} {errorMessage && <p>Error: {errorMessage}</p>}
{audioResult && ( <div> <p>Recording Result:</p> <audio src={URL.createObjectURL(audioResult)} controls /> </div> )} </div> );}
export default AudioRecorder;
Understanding the Example
In the example above:
- We import the
useReactAudioRecorder
hook from the package. - We destructure the hook’s return values:
startRecording
,stopRecording
,audioResult
,status
, anderrorMessage
. - We create two buttons to start and stop recording, with appropriate disabled states.
- We display the recording status when active.
- We show any error messages that might occur.
- When an audio recording is available (
audioResult
), we display an audio player element with the recorded audio.
Managing Recording State
The hook automatically manages the recording state for you through the status
value. This allows you to adapt your UI based on the current recording state:
- When
status
is'idle'
, the recorder is ready to start - When
status
is'recording'
, a recording is in progress - When
status
is'stopped'
, a recording has finished andaudioResult
is available - When
status
is'error'
, an error occurred anderrorMessage
will contain details
Next Steps
For more detailed information about all the values returned by the hook, check out the API Reference section.