@lakshmiprasanth/react-voice-to-text
Version:
A modern React package for voice-to-text conversion with real-time speech recognition and file upload support
516 lines (498 loc) • 16.4 kB
TypeScript
import React$1, { ReactNode } from 'react';
/**
* Simple EventEmitter implementation for browser compatibility
*/
declare class EventEmitter {
private events;
on(event: string, listener: Function): this;
once(event: string, listener: Function): this;
off(event: string, listener: Function): this;
emit(event: string, ...args: any[]): boolean;
removeAllListeners(event?: string): this;
}
/**
* Configuration options for speech recognition engines
*/
interface SpeechRecognitionConfig {
/** Language code (e.g., 'en-US', 'es-ES') */
language?: string;
/** Sample rate for audio processing */
sampleRate?: number;
/** Enable continuous recognition */
continuous?: boolean;
/** Return interim results */
interimResults?: boolean;
/** Maximum number of alternatives to return */
maxAlternatives?: number;
/** Confidence threshold (0-1) */
confidenceThreshold?: number;
/** Custom vocabulary or phrases to improve recognition */
phrases?: string[];
/** Audio encoding format */
encoding?: 'LINEAR16' | 'FLAC' | 'MULAW' | 'AMR' | 'AMR_WB' | 'OGG_OPUS' | 'SPEEX_WITH_HEADER_BYTE';
}
/**
* Speech recognition result
*/
interface SpeechRecognitionResult {
/** Transcribed text */
transcript: string;
/** Confidence score (0-1) */
confidence: number;
/** Whether this is a final result */
isFinal: boolean;
/** Alternative transcriptions */
alternatives?: Array<{
transcript: string;
confidence: number;
}>;
/** Timestamp information */
timestamp?: {
start: number;
end: number;
};
}
/**
* Audio input source configuration
*/
interface AudioInputConfig {
/** Audio source type */
source: 'microphone' | 'file' | 'stream';
/** File path (for file source) */
filePath?: string;
/** Audio stream (for stream source) */
audioStream?: NodeJS.ReadableStream;
/** Device ID (for microphone source) */
deviceId?: string;
/** Recording duration in milliseconds (for microphone) */
duration?: number;
}
/**
* Engine-specific configuration
*/
interface EngineConfig {
/** Engine type */
engine: 'web-speech' | 'vosk' | 'google-cloud' | 'whisper';
/** API key (for cloud services) */
apiKey?: string;
/** Model path (for offline engines like Vosk) */
modelPath?: string;
/** Project ID (for Google Cloud) */
projectId?: string;
/** Custom endpoint URL */
endpoint?: string;
}
/**
* Error types that can occur during speech recognition
*/
declare enum SpeechRecognitionErrorType {
NO_SPEECH = "no-speech",
ABORTED = "aborted",
AUDIO_CAPTURE = "audio-capture",
NETWORK = "network",
NOT_ALLOWED = "not-allowed",
SERVICE_NOT_ALLOWED = "service-not-allowed",
BAD_GRAMMAR = "bad-grammar",
LANGUAGE_NOT_SUPPORTED = "language-not-supported",
ENGINE_ERROR = "engine-error",
INVALID_CONFIG = "invalid-config"
}
/**
* Speech recognition error
*/
declare class SpeechRecognitionError extends Error {
type: SpeechRecognitionErrorType;
originalError?: Error | undefined;
constructor(type: SpeechRecognitionErrorType, message: string, originalError?: Error | undefined);
}
/**
* Events emitted by speech recognition engines
*/
interface SpeechRecognitionEvents {
'start': () => void;
'result': (result: SpeechRecognitionResult) => void;
'end': () => void;
'error': (error: SpeechRecognitionError) => void;
'audiostart': () => void;
'audioend': () => void;
'soundstart': () => void;
'soundend': () => void;
'speechstart': () => void;
'speechend': () => void;
'initialized': () => void;
'started': () => void;
'stopped': () => void;
}
/**
* Base interface for speech recognition engines
*/
interface ISpeechRecognitionEngine extends EventEmitter {
/** Start speech recognition */
start(audioConfig: AudioInputConfig, recognitionConfig?: SpeechRecognitionConfig): Promise<void>;
/** Stop speech recognition */
stop(): Promise<void>;
/** Abort speech recognition */
abort(): Promise<void>;
/** Check if engine is available */
isAvailable(): boolean;
/** Get supported languages */
getSupportedLanguages(): string[];
/** Process audio file directly */
processFile(file: File, config?: SpeechRecognitionConfig): Promise<SpeechRecognitionResult[]>;
/** Process audio stream */
processStream(stream: NodeJS.ReadableStream, config?: SpeechRecognitionConfig): Promise<SpeechRecognitionResult[]>;
}
/**
* Voice-to-text converter options
*/
interface VoiceToTextOptions {
/** Default engine configuration */
defaultEngine?: EngineConfig;
/** Default speech recognition configuration */
defaultRecognitionConfig?: SpeechRecognitionConfig;
/** Enable automatic engine fallback */
enableFallback?: boolean;
/** Engine priority order for fallback */
enginePriority?: Array<EngineConfig['engine']>;
/** Debug mode */
debug?: boolean;
}
/**
* Microphone recording options
*/
interface MicrophoneOptions {
/** Recording duration in milliseconds */
duration?: number;
/** Device ID to use */
deviceId?: string;
/** Sample rate */
sampleRate?: number;
/** Number of channels */
channels?: number;
/** Bit depth */
bitDepth?: number;
/** Audio format */
format?: 'wav' | 'raw';
}
/**
* Browser compatibility information
*/
interface BrowserSupport {
/** Whether Web Speech API is supported */
webSpeechAPI: boolean;
/** Whether MediaRecorder API is supported */
mediaRecorder: boolean;
/** Whether getUserMedia is supported */
getUserMedia: boolean;
/** Browser name and version */
browser: {
name: string;
version: string;
};
}
/**
* Props for VoiceRecorder component
*/
interface VoiceRecorderProps {
/** CSS class name */
className?: string;
/** Whether to show language selector */
showLanguageSelector?: boolean;
/** Whether to show results display */
showResults?: boolean;
/** Whether to show recording controls */
showControls?: boolean;
/** Default language */
language?: string;
/** Enable continuous recording */
continuous?: boolean;
/** Show interim results */
interimResults?: boolean;
/** Callback when result is received */
onResult?: (result: SpeechRecognitionResult) => void;
/** Callback when error occurs */
onError?: (error: string) => void;
/** Callback when recording starts */
onStart?: () => void;
/** Callback when recording stops */
onStop?: () => void;
/** Child components */
children?: React.ReactNode;
}
/**
* Props for FileUpload component
*/
interface FileUploadProps {
/** CSS class name */
className?: string;
/** Callback when file is selected */
onFileSelect?: (file: File) => void;
/** Callback when file is converted */
onConvert?: (file: File, language: string) => Promise<void>;
/** Callback when error occurs */
onError?: (error: string) => void;
/** Accepted file formats */
acceptedFormats?: string[];
/** Maximum file size in bytes */
maxFileSize?: number;
/** Whether to show language selector */
showLanguageSelector?: boolean;
/** Default language */
language?: string;
/** Enable drag and drop */
dragAndDrop?: boolean;
/** Allow multiple file selection */
multiple?: boolean;
/** Whether component is disabled */
disabled?: boolean;
/** Child components */
children?: React.ReactNode;
}
/**
* Props for ResultsDisplay component
*/
interface ResultsDisplayProps {
/** Array of recognition results */
results: SpeechRecognitionResult[];
/** Error message */
error?: string | null;
/** Callback to clear results */
onClear?: () => void;
/** Whether to show clear button */
showClearButton?: boolean;
/** Whether to show confidence scores */
showConfidence?: boolean;
/** Whether to show status (final/interim) */
showStatus?: boolean;
/** Maximum number of results to display */
maxResults?: number;
/** CSS class name */
className?: string;
/** Text to show when no results */
emptyText?: string;
}
/**
* Props for LanguageSelector component
*/
interface LanguageSelectorProps {
/** Selected language value */
value?: string;
/** Callback when language changes */
onChange?: (language: string) => void;
/** Whether component is disabled */
disabled?: boolean;
/** CSS class name */
className?: string;
/** Whether to show label */
showLabel?: boolean;
/** Label text */
label?: string;
/** Placeholder text */
placeholder?: string;
}
/**
* Props for RecordingControls component
*/
interface RecordingControlsProps {
/** Whether currently recording */
isRecording: boolean;
/** Whether currently processing */
isProcessing: boolean;
/** Callback to start recording */
onStart?: () => void;
/** Callback to stop recording */
onStop?: () => void;
/** Whether component is disabled */
disabled?: boolean;
/** CSS class name */
className?: string;
/** Whether to show status */
showStatus?: boolean;
/** Text for start button */
startText?: string;
/** Text for stop button */
stopText?: string;
/** Text for processing state */
processingText?: string;
}
interface VoiceToTextContextType {
isInitialized: boolean;
isRecording: boolean;
isProcessing: boolean;
results: SpeechRecognitionResult[];
error: string | null;
browserSupport: BrowserSupport | null;
startRecording: (options?: Partial<SpeechRecognitionConfig>) => Promise<void>;
stopRecording: () => Promise<void>;
clearResults: () => void;
clearError: () => void;
updateConfig: (config: Partial<VoiceToTextOptions>) => void;
getConfig: () => VoiceToTextOptions;
}
interface VoiceToTextProviderProps {
children: ReactNode;
options?: VoiceToTextOptions;
onResult?: (result: SpeechRecognitionResult) => void;
onError?: (error: string) => void;
onStart?: () => void;
onStop?: () => void;
}
declare const VoiceToTextProvider: React$1.FC<VoiceToTextProviderProps>;
declare const useVoiceToTextContext: () => VoiceToTextContextType;
declare const VoiceRecorder: React$1.FC<VoiceRecorderProps>;
declare const FileUpload: React$1.FC<FileUploadProps>;
interface VoiceToTextConverterProps {
className?: string;
showFileUpload?: boolean;
showVoiceRecorder?: boolean;
showResults?: boolean;
defaultLanguage?: string;
onResult?: (result: SpeechRecognitionResult) => void;
onError?: (error: string) => void;
onStart?: () => void;
onStop?: () => void;
children?: React$1.ReactNode;
}
declare const VoiceToTextConverter: React$1.FC<VoiceToTextConverterProps>;
declare const ResultsDisplay: React$1.FC<ResultsDisplayProps>;
declare const LanguageSelector: React$1.FC<LanguageSelectorProps>;
declare const RecordingControls: React$1.FC<RecordingControlsProps>;
interface UseVoiceToTextOptions extends VoiceToTextOptions {
onResult?: (result: SpeechRecognitionResult) => void;
onError?: (error: string) => void;
onStart?: () => void;
onStop?: () => void;
}
interface UseVoiceToTextReturn {
isInitialized: boolean;
isRecording: boolean;
isProcessing: boolean;
results: SpeechRecognitionResult[];
error: string | null;
browserSupport: BrowserSupport | null;
startRecording: (options?: Partial<SpeechRecognitionConfig>) => Promise<void>;
stopRecording: () => Promise<void>;
clearResults: () => void;
clearError: () => void;
updateConfig: (config: Partial<VoiceToTextOptions>) => void;
getConfig: () => VoiceToTextOptions;
}
declare const useVoiceToText: (options?: UseVoiceToTextOptions) => UseVoiceToTextReturn;
interface UseVoiceRecorderOptions {
language?: string;
continuous?: boolean;
interimResults?: boolean;
onResult?: (result: any) => void;
onError?: (error: string) => void;
onStart?: () => void;
onStop?: () => void;
}
interface UseVoiceRecorderReturn {
isInitialized: boolean;
isRecording: boolean;
isProcessing: boolean;
results: any[];
error: string | null;
startRecording: () => Promise<void>;
stopRecording: () => Promise<void>;
clearResults: () => void;
clearError: () => void;
}
declare const useVoiceRecorder: (options?: UseVoiceRecorderOptions) => UseVoiceRecorderReturn;
interface UseFileUploadOptions {
acceptedFormats?: string[];
maxFileSize?: number;
onFileSelect?: (file: File) => void;
onConvert?: (file: File, language: string) => Promise<any>;
onError?: (error: string) => void;
}
interface UseFileUploadReturn {
selectedFile: File | null;
isConverting: boolean;
results: any[];
error: string | null;
selectFile: (file: File) => void;
convertFile: (language?: string) => Promise<void>;
clearFile: () => void;
clearResults: () => void;
clearError: () => void;
validateFile: (file: File) => {
isValid: boolean;
error?: string;
};
}
declare const useFileUpload: (options?: UseFileUploadOptions) => UseFileUploadReturn;
interface UseSpeechRecognitionOptions {
language?: string;
continuous?: boolean;
interimResults?: boolean;
maxAlternatives?: number;
onResult?: (event: any) => void;
onError?: (event: any) => void;
onStart?: () => void;
onEnd?: () => void;
onAudioStart?: () => void;
onAudioEnd?: () => void;
onSoundStart?: () => void;
onSoundEnd?: () => void;
onSpeechStart?: () => void;
onSpeechEnd?: () => void;
onNoMatch?: () => void;
onNomatch?: () => void;
}
interface UseSpeechRecognitionReturn {
isSupported: boolean;
isListening: boolean;
transcript: string;
finalTranscript: string;
interimTranscript: string;
error: string | null;
start: () => void;
stop: () => void;
abort: () => void;
reset: () => void;
updateConfig: (config: Partial<UseSpeechRecognitionOptions>) => void;
}
declare const useSpeechRecognition: (options?: UseSpeechRecognitionOptions) => UseSpeechRecognitionReturn;
/**
* Check browser support for speech recognition and related APIs
*/
declare function getBrowserSupport(): BrowserSupport;
/**
* Get available audio input devices
*/
declare function getAudioDevices(): Promise<MediaDeviceInfo[]>;
/**
* Request microphone permission
*/
declare function requestMicrophonePermission(): Promise<boolean>;
/**
* Supported audio file formats
*/
declare const SUPPORTED_AUDIO_FORMATS: string[];
/**
* Check if a file is a supported audio format
*/
declare function isSupportedAudioFormat(filePath: string): boolean;
/**
* Check browser capabilities for speech recognition
* @returns Browser support information
*/
declare function checkBrowserSupport(): BrowserSupport;
declare const VERSION = "1.0.0";
declare global {
interface Window {
ReactVoiceToText: {
VoiceToTextConverter: typeof VoiceToTextConverter;
VoiceRecorder: typeof VoiceRecorder;
FileUpload: typeof FileUpload;
useVoiceToText: typeof useVoiceToText;
useVoiceRecorder: typeof useVoiceRecorder;
checkBrowserSupport: typeof checkBrowserSupport;
getAudioDevices: typeof getAudioDevices;
requestMicrophonePermission: typeof requestMicrophonePermission;
};
}
}
export { EventEmitter, FileUpload, LanguageSelector, RecordingControls, ResultsDisplay, SUPPORTED_AUDIO_FORMATS, SpeechRecognitionError, SpeechRecognitionErrorType, VERSION, VoiceRecorder, VoiceToTextConverter, VoiceToTextProvider, checkBrowserSupport, VoiceToTextConverter as default, getAudioDevices, getBrowserSupport, isSupportedAudioFormat, requestMicrophonePermission, useFileUpload, useSpeechRecognition, useVoiceRecorder, useVoiceToText, useVoiceToTextContext };
export type { AudioInputConfig, BrowserSupport, EngineConfig, FileUploadProps, ISpeechRecognitionEngine, LanguageSelectorProps, MicrophoneOptions, RecordingControlsProps, ResultsDisplayProps, SpeechRecognitionConfig, SpeechRecognitionEvents, SpeechRecognitionResult, VoiceRecorderProps, VoiceToTextOptions };