react-voice-recorder-pro
Version:
A powerful React hook-based voice recording library with real-time audio visualization and comprehensive browser support
281 lines (271 loc) • 9.23 kB
TypeScript
interface VoiceRecorderOptions {
/** MIME type of recorded file (default: 'audio/webm') */
mimeType?: string;
/** Smoothing coefficient for audio level measurement (default: 0.8) */
smoothing?: number;
/** FFT size (default: 2048) */
fftSize?: number;
/** Whether to automatically enable microphone (default: false) */
autoEnableMicrophone?: boolean;
/** Whether to automatically play after recording (default: false) */
autoPlayAfterRecording?: boolean;
}
interface VoiceRecorderState {
/** Whether currently recording */
isRecording: boolean;
/** Whether recording is paused */
isPaused: boolean;
/** Whether microphone is enabled */
isMicrophoneEnabled: boolean;
/** Whether audio is playing */
isPlaying: boolean;
/** Microphone permission state */
permission: PermissionState | 'prompt' | 'unknown';
/** Current audio level (0-1) */
audioLevel: number;
/** Recording elapsed time (seconds) */
elapsedTime: number;
/** Formatted recording time (HH:MM:SS) */
formattedTime: string;
/** Recorded audio Blob */
recordedBlob: Blob | null;
/** Audio URL (for playback) */
audioUrl: string | null;
/** Error message */
error: string | null;
}
interface VoiceRecorderControls {
/** Start recording */
startRecording: () => void;
/** Pause recording */
pauseRecording: () => void;
/** Resume recording */
resumeRecording: () => void;
/** Stop recording and return Blob */
stopRecording: () => Promise<Blob | null>;
/** Enable microphone */
enableMicrophone: () => Promise<void>;
/** Disable microphone */
disableMicrophone: () => void;
/** Play/pause recorded audio */
playPause: () => void;
/** Reset recording state */
reset: () => void;
/** Resume audio context (for iOS/Safari) */
resumeAudioContext: () => Promise<void>;
}
interface UseVoiceRecorderReturn extends VoiceRecorderState, VoiceRecorderControls {
/** HTML Audio element reference */
audioRef: React.RefObject<HTMLAudioElement | null>;
}
/**
* All-in-one custom hook for voice recording
*
* Key features:
* - Microphone permission management and stream control
* - Real-time audio level measurement and visualization
* - Recording start/stop/pause/resume functionality
* - Recording time tracking and formatting
* - Recorded audio playback functionality
* - Error handling and state management
* - iOS/Safari compatibility support
*/
declare function useVoiceRecorder(options?: VoiceRecorderOptions): UseVoiceRecorderReturn;
/**
* Custom hook for managing Web Audio API AudioContext lifecycle
*
* Key features:
* - Automatically manages AudioContext creation and cleanup
* - Real-time tracking of context execution state via statechange events
* - Provides resume functionality for iOS/Safari user gesture requirements
* - Supports webkitAudioContext for browser compatibility
*/
declare function useAudioContext(): {
audioContext: AudioContext | null;
isRunning: boolean;
resume: () => Promise<void>;
};
/**
* Custom hook that calculates RMS level (0..1) based on time-domain waveform of microphone stream
*
* Key features:
* - Configures AnalyserNode internally and polls in real-time with requestAnimationFrame
* - Provides basic analysis parameters like smoothing, fftSize for audio analysis quality control
* - Safely cleans up on stream/context changes or component unmount to prevent memory leaks
* - Accurate audio level measurement based on RMS (Root Mean Square)
*/
declare function useAudioMeter(params: {
audioContext: AudioContext | null;
stream: MediaStream | null;
smoothing?: number;
fftSize?: number;
}): {
level: number;
};
interface UseAudioPlayerReturn {
isPlaying: boolean;
audioRef: React.RefObject<HTMLAudioElement | null>;
playPause: () => void;
resetPlayer: () => void;
handleAudioEnded: () => void;
}
/**
* Custom hook for managing audio playback
*
* Key features:
* - Manages play/pause state of audio files
* - Provides HTML Audio element reference
* - Automatic pause handling on playback completion
* - Player state reset functionality
*/
declare function useAudioPlayer(): UseAudioPlayerReturn;
type RecorderState = {
isRecording: boolean;
isPaused: boolean;
chunks: Blob[];
mimeType: string;
start: () => void;
pause: () => void;
resume: () => void;
stop: () => Promise<Blob | null>;
reset: () => void;
error: string | null;
};
/**
* Custom hook for audio recording based on MediaRecorder API
*
* Key features:
* - Provides start/stop/pause/resume recording functionality
* - Collects audio data chunks through dataavailable events
* - Creates final audio file in Blob format
* - Automatically cleans up previous recorder when stream changes to prevent memory leaks
* - Error handling and state management
*/
declare function useMediaRecorder(stream: MediaStream | null, // Media stream to record
options?: MediaRecorderOptions): RecorderState;
type MicrophoneState = {
stream: MediaStream | null;
isEnabled: boolean;
permission: PermissionState | 'prompt' | 'unknown';
error: string | null;
enable: () => Promise<void>;
disable: () => void;
};
declare function useMicrophone(): MicrophoneState;
/**
* Custom hook for tracking recording progress time
*
* Key features:
* - Automatically starts/stops timer based on recording start/stop
* - Supports pause/resume functionality for accurate recording time tracking
* - Formats time in HH:MM:SS format for user display
* - Safely cleans up timer on component unmount
*/
declare function useRecordingTimer(isRecording: boolean, // Whether currently recording
isPaused?: boolean): {
elapsedTime: number;
formattedTime: string;
reset: () => void;
};
interface AudioFormat {
/** MIME type */
mimeType: string;
/** File extension */
extension: string;
/** Browser support status */
supported: boolean;
}
declare const SUPPORTED_AUDIO_FORMATS: AudioFormat[];
interface VoiceRecorderError {
code: string;
message: string;
details?: any;
}
interface VoiceRecorderEvents {
onRecordingStart?: () => void;
onRecordingPause?: () => void;
onRecordingResume?: () => void;
onRecordingStop?: (blob: Blob) => void;
onMicrophoneEnabled?: () => void;
onMicrophoneDisabled?: () => void;
onError?: (error: VoiceRecorderError) => void;
onAudioLevelChange?: (level: number) => void;
}
interface VoiceRecorderConfig {
/** MIME type of recorded file */
mimeType?: string;
/** Smoothing coefficient for audio level measurement */
smoothing?: number;
/** FFT size */
fftSize?: number;
/** Whether to automatically enable microphone */
autoEnableMicrophone?: boolean;
/** Whether to automatically play after recording */
autoPlayAfterRecording?: boolean;
/** Event handlers */
events?: VoiceRecorderEvents;
/** Maximum recording time (seconds, 0 for unlimited) */
maxRecordingTime?: number;
/** Minimum recording time (seconds) */
minRecordingTime?: number;
/** Recording quality setting */
quality?: 'low' | 'medium' | 'high';
}
/**
* Check audio formats supported by browser
*/
declare function getSupportedAudioFormats(): AudioFormat[];
/**
* Select optimal audio format
*/
declare function getBestAudioFormat(): string;
/**
* Download Blob
*/
declare function downloadBlob(blob: Blob, filename?: string): void;
/**
* Convert Blob to Base64 string
*/
declare function blobToBase64(blob: Blob): Promise<string>;
/**
* Convert Base64 string to Blob
*/
declare function base64ToBlob(base64: string, mimeType?: string): Blob;
/**
* Format file size in human-readable form
*/
declare function formatFileSize(bytes: number): string;
/**
* Format time in human-readable form
*/
declare function formatDuration(seconds: number): string;
/**
* Convert audio level for visualization
*/
declare function normalizeAudioLevel(level: number, minLevel?: number): number;
/**
* Check if browser supports MediaRecorder
*/
declare function isMediaRecorderSupported(): boolean;
/**
* Check if browser supports getUserMedia
*/
declare function isGetUserMediaSupported(): boolean;
/**
* Check if browser supports Web Audio API
*/
declare function isWebAudioSupported(): boolean;
/**
* Get device information
*/
declare function getDeviceInfo(): {
userAgent: string;
isMobile: boolean;
isIOS: boolean;
isAndroid: boolean;
isSafari: boolean;
isChrome: boolean;
isFirefox: boolean;
};
export { SUPPORTED_AUDIO_FORMATS, base64ToBlob, blobToBase64, downloadBlob, formatDuration, formatFileSize, getBestAudioFormat, getDeviceInfo, getSupportedAudioFormats, isGetUserMediaSupported, isMediaRecorderSupported, isWebAudioSupported, normalizeAudioLevel, useAudioContext, useAudioMeter, useAudioPlayer, useMediaRecorder, useMicrophone, useRecordingTimer, useVoiceRecorder };
export type { AudioFormat, UseVoiceRecorderReturn, VoiceRecorderConfig, VoiceRecorderControls, VoiceRecorderError, VoiceRecorderEvents, VoiceRecorderOptions, VoiceRecorderState };