https://github.com/noorjsdivs/react-native-voice-ts
React Native Native Voice library for iOS and Android
https://github.com/noorjsdivs/react-native-voice-ts
android ios react-native react-native-voice react-native-voice-ts
Last synced: 4 months ago
JSON representation
React Native Native Voice library for iOS and Android
- Host: GitHub
- URL: https://github.com/noorjsdivs/react-native-voice-ts
- Owner: noorjsdivs
- License: mit
- Created: 2025-12-23T04:22:04.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2025-12-24T07:22:38.000Z (7 months ago)
- Last Synced: 2025-12-25T19:45:04.868Z (7 months ago)
- Topics: android, ios, react-native, react-native-voice, react-native-voice-ts
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/react-native-voice-ts
- Size: 1.09 MB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# π€ React Native Voice (TypeScript)
### Advanced Speech-to-Text Library for React Native
[](https://www.npmjs.com/package/react-native-voice-ts)
[](https://www.npmjs.com/package/react-native-voice-ts)
[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
[](https://github.com/noorjsdivs/react-native-voice-ts/pulls)
A powerful, production-ready speech-to-text library for React Native applications with full TypeScript support, built-in performance optimizations, and comprehensive features.
[Features](#-features) β’
[Installation](#-installation) β’
[Quick Start](#-quick-start) β’
[Component Usage](#-component--hook-usage) β’
[API Reference](#-api-reference) β’
[Examples](#-complete-examples) β’
[Contributing](#-contributing)
---
### β¨ Features
### Core Capabilities
- π― **Real-time Speech Recognition** - Live speech-to-text conversion
- π **Partial Results** - Get intermediate results as the user speaks
- π **Volume Monitoring** - Track audio input levels in real-time
- π **Multi-language Support** - Support for 100+ languages
- β‘ **Performance Optimized** - Built with performance best practices
- π± **Cross-platform** - Works on both iOS and Android
- π **Type-safe** - Full TypeScript support with comprehensive types
### Enhanced Features (2025 Update)
- β
**Permission Management** - Easy microphone permission handling
- π **Performance Tracking** - Monitor recognition duration and state
- πΎ **Result Caching** - Access last results without re-recognition
- π¨ **Modern API** - Clean, intuitive API design
- π‘οΈ **Error Handling** - Comprehensive error management
- π§ **Fully Customizable** - Extensive configuration options
- πͺ **Ready-to-use Components** - VoiceMicrophone component & useVoiceRecognition hook
- π **Plug & Play** - Import and use instantly in any React Native app
- π― **SVG Icons Included** - Beautiful Lucide-based mic icons (MicIcon, MicOffIcon)
### Platform Support
| Feature | iOS | Android |
| --------------------- | :-: | :-----: |
| Speech Recognition | β
| β
|
| Partial Results | β
| β
|
| Volume Events | β
| β
|
| Permission Management | N/A | β
|
| Audio Transcription | β
| β |
| Recognition Services | β | β
|
---
## π¦ Installation
### Using npm
```bash
npm install react-native-voice-ts --save
```
### Using yarn
```bash
yarn add react-native-voice-ts
```
### Using pnpm
```bash
pnpm add react-native-voice-ts
```
### iOS Setup
```bash
cd ios && pod install && cd ..
```
### Permissions
#### iOS (Info.plist)
```xml
NSMicrophoneUsageDescription
This app needs access to your microphone for voice recognition
NSSpeechRecognitionUsageDescription
This app needs speech recognition permission to convert your speech to text
```
#### Android (AndroidManifest.xml)
```xml
```
### π± Compatibility
**React Native Versions**: 0.71.0 and above
| React Native | iOS | Android | Status |
| ------------ | -------- | ---------- | ------------- |
| 0.76.x | β
13.4+ | β
API 24+ | Full Support |
| 0.75.x | β
13.4+ | β
API 24+ | Full Support |
| 0.74.x | β
13.4+ | β
API 24+ | Full Support |
| 0.73.x | β
13.4+ | β
API 24+ | Full Support |
| 0.72.x | β
13.4+ | β
API 24+ | Full Support |
| 0.71.x | β
13.4+ | β
API 24+ | Full Support |
| < 0.71 | β | β | Not Supported |
**Architecture Support**:
- β
Old Architecture (Bridge) - Fully Supported
- β
New Architecture (Turbo Modules & Fabric) - Fully Supported
- β
Expo Projects (48.0.0+) - Supported with config plugin
**Platform Requirements**:
- **iOS**: 13.4 or higher
- **Android**: API Level 24 (Android 7.0) or higher
- **Node.js**: 18.0.0 or higher
For detailed compatibility information and migration guides, see [COMPATIBILITY.md](./COMPATIBILITY.md).
---
## π Quick Start
### Three Ways to Use
```typescript
// 1. Ready-to-use Component (Easiest - New in 2025)
import { VoiceMicrophone } from 'react-native-voice-ts';
// 2. Custom Hook (More control - New in 2025)
import { useVoiceRecognition } from 'react-native-voice-ts';
// 3. Core API (Advanced - Fully backward compatible)
import Voice from 'react-native-voice-ts';
// 4. Import SVG Icons (Optional - for custom UI)
import { MicIcon, MicOffIcon } from 'react-native-voice-ts';
```
**Note:** To use SVG icons, install `react-native-svg`:
```bash
npm install react-native-svg
# or
yarn add react-native-svg
```
---
### β‘ Super Simple - Just Import and Use!
**Example 1: Voice Search (Minimal Code)**
```tsx
import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
export default function App() {
const [searchText, setSearchText] = useState('');
return (
{({ isRecording, start, stop }) => (
)}
);
}
```
**Example 2: With Custom Styling & SVG Icons**
```tsx
import React, { useState } from 'react';
import { View, TextInput, TouchableOpacity, StyleSheet } from 'react-native';
import { VoiceMicrophone, MicIcon, MicOffIcon } from 'react-native-voice-ts';
export default function App() {
const [text, setText] = useState('');
return (
{({ isRecording, start, stop }) => (
{isRecording ? (
) : (
)}
)}
);
}
const styles = StyleSheet.create({
container: { flexDirection: 'row', padding: 20 },
input: { flex: 1, borderWidth: 1, padding: 10, marginRight: 10 },
mic: {
width: 50,
height: 50,
borderRadius: 25,
backgroundColor: '#007AFF',
justifyContent: 'center',
alignItems: 'center',
},
recording: { backgroundColor: '#FF3B30' },
});
```
---
## π¨ Built-in Icon Variants
The library includes **3 microphone icon variants**, each with on/off states (6 icons total):
### **Variant 1: Standard Outline** (Default)
Classic microphone with clean outline design.
```tsx
import { MicIcon, MicOffIcon } from 'react-native-voice-ts';
// Active state
// Muted/Off state
```
**SVG Preview:**
Active
Muted
### **Variant 2: Filled Microphone**
Bold filled microphone for emphasis and better visibility.
```tsx
import { MicIconFilled, MicOffIconFilled } from 'react-native-voice-ts';
// Active filled state
// Muted filled state
```
**SVG Preview:**
```
Active: βͺββ₯ (Solid filled microphone)
Muted: βͺ/ββ₯ (Filled microphone with mute indicator)
```
Active
Muted
### **Variant 3: Microphone with Sound Waves**
Dynamic microphone with sound wave indicators - perfect for showing active recording.
```tsx
import { MicIconWave, MicOffIconWave } from 'react-native-voice-ts';
// Active with waves
// Muted with disabled waves
```
**SVG Preview:**
```
Active: ββͺ β₯β (Microphone with animated sound waves)
Muted: ββͺ/β₯β (Microphone with muted/dashed waves)
```
### **Complete Icon Usage Example**
```tsx
import React, { useState } from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
import {
VoiceMicrophone,
MicIcon,
MicOffIcon,
MicIconFilled,
MicOffIconFilled,
MicIconWave,
MicOffIconWave,
} from 'react-native-voice-ts';
export default function IconVariantsDemo() {
const [variant, setVariant] = useState<'standard' | 'filled' | 'wave'>(
'standard',
);
const getIcons = () => {
switch (variant) {
case 'filled':
return { ActiveIcon: MicIconFilled, MutedIcon: MicOffIconFilled };
case 'wave':
return { ActiveIcon: MicIconWave, MutedIcon: MicOffIconWave };
default:
return { ActiveIcon: MicIcon, MutedIcon: MicOffIcon };
}
};
const { ActiveIcon, MutedIcon } = getIcons();
return (
{/* Icon Variant Selector */}
setVariant('standard')}>
Standard
setVariant('filled')}>
Filled
setVariant('wave')}>
Wave
{/* Voice Input with Selected Icon */}
{({ isRecording, start, stop }) => (
{isRecording ? (
) : (
)}
)}
);
}
const styles = StyleSheet.create({
container: { padding: 20, alignItems: 'center' },
selector: { flexDirection: 'row', gap: 15, marginBottom: 20 },
active: { fontWeight: 'bold', color: '#007AFF' },
micButton: {
width: 70,
height: 70,
borderRadius: 35,
backgroundColor: '#007AFF',
justifyContent: 'center',
alignItems: 'center',
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
recording: { backgroundColor: '#FF3B30' },
});
```
### **Icon Props**
All icons accept the same props:
| Prop | Type | Default | Description |
| ------------- | -------- | ---------------- | ---------------------------- |
| `size` | `number` | `24` | Icon size in pixels |
| `color` | `string` | `'currentColor'` | Icon color (any valid color) |
| `strokeWidth` | `number` | `2` | Stroke width for outlines |
---
### π― Using Hook (For More Control)
```tsx
import React from 'react';
import { View, Text, Button } from 'react-native';
import { useVoiceRecognition } from 'react-native-voice-ts';
export default function App() {
const { isRecording, results, start, stop } = useVoiceRecognition({
onResult: (text) => console.log('You said:', text),
});
return (
{results[0] || 'Press to speak'}
);
}
```
---
### π§ Advanced (Core API)
For users who want full control or are migrating from previous versions:
```tsx
import React, { useEffect, useState } from 'react';
import { View, Text, Button } from 'react-native';
import Voice from 'react-native-voice-ts';
export default function App() {
const [text, setText] = useState('');
useEffect(() => {
Voice.onSpeechResults = (e) => setText(e.value[0]);
return () => Voice.destroy().then(Voice.removeAllListeners);
}, []);
return (
{text}
Voice.start('en-US')} title="Start" />
Voice.stop()} title="Stop" />
);
}
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
text: {
fontSize: 24,
marginBottom: 40,
textAlign: 'center',
},
button: {
backgroundColor: '#007AFF',
padding: 20,
borderRadius: 50,
width: 100,
height: 100,
justifyContent: 'center',
alignItems: 'center',
},
recording: {
backgroundColor: '#FF3B30',
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
},
});
export default App;
```
---
## π API Reference
### Components
#### VoiceMicrophone
A ready-to-use React component that handles all voice recognition logic.
**Props:**
| Prop | Type | Default | Description |
| ---------------------- | ------------------------- | --------- | ----------------------------------------------------- |
| `onSpeechResult` | `(text: string) => void` | - | Callback when final speech result is available |
| `onPartialResult` | `(text: string) => void` | - | Callback when partial (real-time) result is available |
| `onStart` | `() => void` | - | Callback when recording starts |
| `onStop` | `() => void` | - | Callback when recording stops |
| `onError` | `(error: string) => void` | - | Callback when an error occurs |
| `locale` | `string` | `'en-US'` | Language locale for recognition |
| `autoStart` | `boolean` | `false` | Auto-start recording on mount |
| `enablePartialResults` | `boolean` | `true` | Enable real-time partial results |
| `children` | `function` | - | Render prop function |
**Children Render Props:**
```typescript
{
isRecording: boolean; // Whether recording is active
recognizedText: string; // Final recognized text
partialText: string; // Real-time partial text
start: () => Promise; // Start recording
stop: () => Promise; // Stop recording
cancel: () => Promise; // Cancel recording
error: string | null; // Error message if any
}
```
**Example:**
```typescript
console.log(text)}
>
{({ isRecording, start, stop }) => (
)}
```
### Hooks
#### useVoiceRecognition
A custom hook that provides voice recognition functionality.
**Options:**
| Option | Type | Default | Description |
| ---------------------- | ------------------------- | --------- | ---------------------- |
| `locale` | `string` | `'en-US'` | Language locale |
| `enablePartialResults` | `boolean` | `true` | Enable partial results |
| `onResult` | `(text: string) => void` | - | Result callback |
| `onError` | `(error: string) => void` | - | Error callback |
**Returns:**
```typescript
{
isRecording: boolean;
results: string[];
partialResults: string[];
error: string | null;
start: () => Promise;
stop: () => Promise;
cancel: () => Promise;
reset: () => void;
}
```
**Example:**
```typescript
const { isRecording, results, start, stop } = useVoiceRecognition({
locale: 'en-US',
onResult: (text) => setSearchQuery(text),
});
```
---
### Core API Methods
#### Core Methods
##### `start(locale: string, options?: VoiceOptions): Promise`
Start voice recognition.
```typescript
// Basic usage
await Voice.start('en-US');
// With options (Android)
await Voice.start('en-US', {
EXTRA_LANGUAGE_MODEL: 'LANGUAGE_MODEL_FREE_FORM',
EXTRA_MAX_RESULTS: 5,
EXTRA_PARTIAL_RESULTS: true,
REQUEST_PERMISSIONS_AUTO: true,
});
```
**Supported Languages**: `en-US`, `es-ES`, `fr-FR`, `de-DE`, `it-IT`, `ja-JP`, `ko-KR`, `pt-BR`, `ru-RU`, `zh-CN`, and 100+ more.
##### `stop(): Promise`
Stop voice recognition and get final results.
```typescript
await Voice.stop();
```
##### `cancel(): Promise`
Cancel voice recognition without getting results.
```typescript
await Voice.cancel();
```
##### `destroy(): Promise`
Destroy the voice recognition instance and cleanup.
```typescript
await Voice.destroy();
```
##### `removeAllListeners(): void`
Remove all event listeners.
```typescript
Voice.removeAllListeners();
```
#### Status Methods
##### `isAvailable(): Promise<0 | 1>`
Check if speech recognition is available on the device.
```typescript
const available = await Voice.isAvailable();
if (available) {
console.log('Speech recognition is available');
}
```
##### `isRecognizing(): Promise<0 | 1>`
Check if currently recognizing (async).
```typescript
const recognizing = await Voice.isRecognizing();
```
##### `recognizing: boolean` (getter)
Check if currently recognizing (synchronous).
```typescript
if (Voice.recognizing) {
console.log('Currently recording');
}
```
#### New Features (2025)
##### `requestMicrophonePermission(): Promise`
Request microphone permission (Android only).
```typescript
const granted = await Voice.requestMicrophonePermission();
if (granted) {
await Voice.start('en-US');
}
```
##### `checkMicrophonePermission(): Promise`
Check microphone permission status (Android only).
```typescript
const hasPermission = await Voice.checkMicrophonePermission();
```
##### `getRecognitionDuration(): number`
Get the duration of current recognition session in milliseconds.
```typescript
const duration = Voice.getRecognitionDuration();
console.log(`Recording for ${duration}ms`);
```
##### `getLastResults(): string[]`
Get the last recognized results without triggering new recognition.
```typescript
const lastResults = Voice.getLastResults();
console.log('Last results:', lastResults);
```
#### Android-Only Methods
##### `getSpeechRecognitionServices(): Promise`
Get available speech recognition engines on Android.
```typescript
if (Platform.OS === 'android') {
const services = await Voice.getSpeechRecognitionServices();
console.log('Available services:', services);
}
```
### Events
Set up event listeners to handle voice recognition events:
#### `onSpeechStart`
Triggered when speech recognition starts.
```typescript
Voice.onSpeechStart = (e: SpeechStartEvent) => {
console.log('Speech recognition started');
};
```
#### `onSpeechRecognized`
Triggered when speech is recognized.
```typescript
Voice.onSpeechRecognized = (e: SpeechRecognizedEvent) => {
console.log('Speech recognized');
};
```
#### `onSpeechEnd`
Triggered when speech recognition ends.
```typescript
Voice.onSpeechEnd = (e: SpeechEndEvent) => {
console.log('Speech recognition ended');
};
```
#### `onSpeechError`
Triggered when an error occurs.
```typescript
Voice.onSpeechError = (e: SpeechErrorEvent) => {
console.error('Error:', e.error?.message);
};
```
#### `onSpeechResults`
Triggered when final results are available.
```typescript
Voice.onSpeechResults = (e: SpeechResultsEvent) => {
console.log('Results:', e.value);
// e.value is an array of strings, sorted by confidence
};
```
#### `onSpeechPartialResults`
Triggered when partial results are available (real-time).
```typescript
Voice.onSpeechPartialResults = (e: SpeechResultsEvent) => {
console.log('Partial results:', e.value);
};
```
#### `onSpeechVolumeChanged`
Triggered when the audio volume changes.
```typescript
Voice.onSpeechVolumeChanged = (e: SpeechVolumeChangeEvent) => {
console.log('Volume:', e.value); // 0-10
};
```
### Types
```typescript
import type {
SpeechEvents,
SpeechStartEvent,
SpeechEndEvent,
SpeechResultsEvent,
SpeechErrorEvent,
SpeechRecognizedEvent,
SpeechVolumeChangeEvent,
VoiceOptions,
RecognitionStats,
PermissionResult,
Language,
} from 'react-native-voice-ts';
```
---
## π‘ More Examples
### Example 1: Simple Voice Search
```tsx
import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
function VoiceSearch() {
const [query, setQuery] = useState('');
return (
{({ isRecording, start, stop }) => (
)}
);
}
```
### Example 2: Real-time Transcription
```tsx
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
function LiveTranscription() {
const [text, setText] = useState('');
return (
console.log('Live:', live)}
>
{({ isRecording, partialText, start, stop }) => (
<>
{isRecording ? partialText : text}
>
)}
);
}
```
### Example 3: Multi-Language
```tsx
import React, { useState } from 'react';
import { View, Text, Button, Picker } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
function MultiLanguage() {
const [lang, setLang] = useState('en-US');
const [text, setText] = useState('');
return (
{text}
{({ isRecording, start, stop }) => (
)}
);
}
```
### Example 4: Voice Form
```tsx
import React, { useState } from 'react';
import { View, TextInput, Button } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
function VoiceForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [active, setActive] = useState(null);
return (
{({ isRecording, start, stop }) => (
)}
{({ isRecording, start, stop }) => (
)}
);
}
```
### Example 5: Using the Hook
```tsx
import React from 'react';
import { View, Text, Button } from 'react-native';
import { useVoiceRecognition } from 'react-native-voice-ts';
function HookExample() {
const { isRecording, results, partialResults, start, stop, reset } =
useVoiceRecognition({
locale: 'en-US',
onResult: (text) => console.log(text),
});
return (
{isRecording ? partialResults[0] : results[0]}
);
}
```
**More examples in the repo:**
- [VoiceSearchExample.tsx](./example/src/VoiceSearchExample.tsx) - Full search bar implementation
- [VoiceHookExample.tsx](./example/src/VoiceHookExample.tsx) - Hook usage with advanced features
- [COMPONENT_USAGE.md](./COMPONENT_USAGE.md) - Comprehensive component guide
---
## π‘ More Examples
### Example 1: Simple Voice Search
```typescript
import React, { useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, ScrollView } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
const MultiLanguageVoice = () => {
const [selectedLanguage, setSelectedLanguage] = useState('en-US');
const [text, setText] = useState('');
const languages = [
{ code: 'en-US', name: 'English (US)', flag: 'πΊπΈ' },
{ code: 'es-ES', name: 'Spanish', flag: 'πͺπΈ' },
{ code: 'fr-FR', name: 'French', flag: 'π«π·' },
{ code: 'de-DE', name: 'German', flag: 'π©πͺ' },
{ code: 'zh-CN', name: 'Chinese', flag: 'π¨π³' },
{ code: 'ja-JP', name: 'Japanese', flag: 'π―π΅' },
];
return (
Multi-language Voice Input
{languages.map((lang) => (
setSelectedLanguage(lang.code)}
>
{lang.flag}
{lang.name}
))}
{text || 'Select language and speak...'}
{({ isRecording, start, stop }) => (
{isRecording ? 'βΉ' : 'π€'}
{isRecording ? 'Stop' : 'Start Recording'}
)}
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#fff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
textAlign: 'center',
},
langScroll: {
marginBottom: 20,
},
langButton: {
padding: 10,
marginRight: 10,
borderRadius: 10,
backgroundColor: '#f0f0f0',
alignItems: 'center',
minWidth: 100,
},
selectedLang: {
backgroundColor: '#007AFF',
},
flag: {
fontSize: 30,
marginBottom: 5,
},
langName: {
fontSize: 12,
},
resultContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f9f9f9',
borderRadius: 10,
padding: 20,
marginBottom: 20,
},
resultText: {
fontSize: 18,
textAlign: 'center',
},
micButton: {
backgroundColor: '#007AFF',
padding: 20,
borderRadius: 50,
alignItems: 'center',
},
recording: {
backgroundColor: '#FF3B30',
},
micIcon: {
fontSize: 40,
},
micText: {
color: '#fff',
marginTop: 10,
fontSize: 16,
fontWeight: 'bold',
},
});
```
### Example 4: Using Custom Hook with Form Input
```typescript
import React, { useState } from 'react';
import { View, TextInput, TouchableOpacity, Text, StyleSheet } from 'react-native';
import { useVoiceRecognition } from 'react-native-voice-ts';
const VoiceForm = () => {
const [name, setName] = useState('');
const [message, setMessage] = useState('');
const [activeField, setActiveField] = useState<'name' | 'message' | null>(null);
const { isRecording, results, start, stop } = useVoiceRecognition({
locale: 'en-US',
onResult: (text) => {
if (activeField === 'name') {
setName(text);
} else if (activeField === 'message') {
setMessage(text);
}
setActiveField(null);
},
});
const startRecordingForField = (field: 'name' | 'message') => {
setActiveField(field);
start();
};
return (
Voice Form
Name:
isRecording ? stop() : startRecordingForField('name')
}
>
π€
Message:
isRecording ? stop() : startRecordingForField('message')
}
>
π€
console.log({ name, message })}
>
Submit
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#fff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 30,
textAlign: 'center',
},
inputGroup: {
marginBottom: 20,
},
label: {
fontSize: 16,
marginBottom: 8,
fontWeight: '600',
},
inputRow: {
flexDirection: 'row',
alignItems: 'center',
},
input: {
flex: 1,
borderWidth: 1,
borderColor: '#ddd',
padding: 12,
borderRadius: 8,
marginRight: 10,
},
textArea: {
height: 100,
textAlignVertical: 'top',
},
micBtn: {
width: 45,
height: 45,
borderRadius: 22.5,
backgroundColor: '#007AFF',
justifyContent: 'center',
alignItems: 'center',
},
recording: {
backgroundColor: '#FF3B30',
},
submitButton: {
backgroundColor: '#34C759',
padding: 15,
borderRadius: 8,
alignItems: 'center',
marginTop: 20,
},
submitText: {
color: '#fff',
fontSize: 18,
fontWeight: 'bold',
},
});
```
### Example 5: Voice Commands (Advanced)
```typescript
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
import { VoiceMicrophone } from 'react-native-voice-ts';
const VoiceCommands = () => {
const [command, setCommand] = useState('');
const [history, setHistory] = useState([]);
useEffect(() => {
if (command) {
handleCommand(command);
}
}, [command]);
const handleCommand = (text: string) => {
const lowerText = text.toLowerCase();
if (lowerText.includes('hello') || lowerText.includes('hi')) {
addToHistory('π Hello there!');
} else if (lowerText.includes('time')) {
addToHistory(`π Current time: ${new Date().toLocaleTimeString()}`);
} else if (lowerText.includes('date')) {
addToHistory(`π
Today's date: ${new Date().toLocaleDateString()}`);
} else if (lowerText.includes('clear')) {
setHistory([]);
} else {
addToHistory(`β Unknown command: "${text}"`);
}
};
const addToHistory = (message: string) => {
setHistory((prev) => [message, ...prev]);
};
return (
Voice Commands
Try: "Hello", "What time is it?", "What's the date?", "Clear"
{({ isRecording, recognizedText, start, stop }) => (
{isRecording ? 'π΄ Listening...' : 'π€ Speak Command'}
{recognizedText && (
"{recognizedText}"
)}
)}
index.toString()}
renderItem={({ item }) => (
{item}
)}
ListEmptyComponent={
No commands yet...
}
/>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: '#fff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 10,
},
subtitle: {
fontSize: 12,
color: '#666',
textAlign: 'center',
marginBottom: 20,
},
controlPanel: {
marginBottom: 20,
},
button: {
backgroundColor: '#007AFF',
padding: 15,
borderRadius: 10,
alignItems: 'center',
},
recording: {
backgroundColor: '#FF3B30',
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: 'bold',
},
recognizedText: {
textAlign: 'center',
marginTop: 10,
fontSize: 14,
color: '#666',
fontStyle: 'italic',
},
list: {
flex: 1,
},
historyItem: {
backgroundColor: '#f0f0f0',
padding: 15,
borderRadius: 8,
marginBottom: 10,
},
historyText: {
fontSize: 16,
},
emptyText: {
textAlign: 'center',
color: '#999',
marginTop: 50,
fontSize: 16,
},
});
```
**More examples in the repo:**
- [VoiceSearchExample.tsx](./example/src/VoiceSearchExample.tsx) - Full search bar implementation
- [VoiceHookExample.tsx](./example/src/VoiceHookExample.tsx) - Hook usage with advanced features
- [COMPONENT_USAGE.md](./COMPONENT_USAGE.md) - Comprehensive component guide
---
## π¦ Component & Hook Usage
### Quick Links
- **[Complete Component Usage Guide](./COMPONENT_USAGE.md)** - Comprehensive guide with real-world examples
- **[VoiceSearchExample](./example/src/VoiceSearchExample.tsx)** - Working search bar example
- **[VoiceHookExample](./example/src/VoiceHookExample.tsx)** - Working hook usage example
### Component Benefits
β
**No boilerplate** - Works out of the box
β
**Automatic cleanup** - Handles all event listeners
β
**Permission handling** - Built-in permission checks
β
**Type-safe** - Full TypeScript support
β
**Customizable** - Use your own UI with render props
---
## π Backward Compatibility
**This library is fully backward compatible!** If you're upgrading from a previous version or the original `@react-native-voice/voice`, all your existing code will continue to work without any changes.
### Core API (Always Supported)
The core Voice API remains unchanged and fully supported:
```tsx
import Voice from 'react-native-voice-ts';
// All these work exactly as before
Voice.start('en-US');
Voice.stop();
Voice.cancel();
Voice.destroy();
Voice.isAvailable();
Voice.onSpeechResults = (e) => console.log(e.value);
```
### What's New in v1.0+
The new features are **additions** that don't break existing code:
```tsx
// β
NEW: Component (optional to use)
import { VoiceMicrophone } from 'react-native-voice-ts';
// β
NEW: Hook (optional to use)
import { useVoiceRecognition } from 'react-native-voice-ts';
// β
NEW: Icons (optional to use)
import { MicIcon, MicOffIcon } from 'react-native-voice-ts';
// β
Still works: Original API
import Voice from 'react-native-voice-ts';
```
### Migration Guide
**No migration needed!** But if you want to use the new features:
```tsx
// Before (still works)
import Voice from 'react-native-voice-ts';
Voice.onSpeechResults = (e) => setText(e.value[0]);
Voice.start('en-US');
// After (optional upgrade)
import { useVoiceRecognition } from 'react-native-voice-ts';
const { isRecording, results, start } = useVoiceRecognition({
onResult: setText,
});
```
---
## β οΈ Common Issues & Solutions
### Issue: No speech detected
**Solution**: Check microphone permissions and ensure the device is not muted.
### Issue: Error on iOS Simulator
**Solution**: Speech recognition doesn't work on iOS Simulator. Use a real device.
### Issue: Partial results not working
**Solution**: Ensure `EXTRA_PARTIAL_RESULTS: true` is set on Android.
### Issue: App crashes on Android
**Solution**: Make sure RECORD_AUDIO permission is declared in AndroidManifest.xml.
---
## π€ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
### Development Setup
```bash
# Clone the repository
git clone https://github.com/noorjsdivs/react-native-voice-ts.git
cd react-native-voice-ts
# Install dependencies
yarn install
# Build
yarn build
# Run example
cd example
yarn install
yarn ios # or yarn android
```
---
## π License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Copyright (c) 2025 Noor Mohammad
---
## π€ Author
**Noor Mohammad**
- GitHub: [@noorjsdivs](https://github.com/noorjsdivs)
- Email: noor.jsdivs@gmail.com
---
## π Acknowledgments
- Thanks to all contributors who have helped improve this library
- Inspired by the need for better voice recognition in React Native apps
- Built with β€οΈ for the React Native community
---
## π Stats





---