react-native-voice-search
v0.1.0
Published
Lightweight React Native voice-enabled search component using Android SpeechRecognizer and iOS SFSpeechRecognizer (New Architecture Turbo Module)
Maintainers
Keywords
Readme
react-native-voice-search
Voice-enabled search for React Native using platform speech APIs only:
- Android —
SpeechRecognizer - iOS —
SFSpeechRecognizer
No Whisper, FFmpeg, TensorFlow, ONNX, or bundled speech models. Default search and mic icons are small PNGs included in the package.
Requirements
- React Native New Architecture (TurboModules + Codegen) — no old-bridge fallback
- Tested with React Native 0.85
- Speech must be tested on a physical device
Installation
npm install react-native-voice-search
# or
yarn add react-native-voice-searchThen in your app (not this library):
cd ios && pod installRebuild the native app after install. A Metro reload is not enough.
Autolinking handles native linking. Your app must already have New Architecture enabled.
Permissions
Edit files in your React Native app. Runtime prompts still appear on first use (mic button or Voice.requestPermissions()).
Android
File to edit:
android/app/src/main/AndroidManifest.xmlOpen that file and paste the permission + <queries> block as direct children of <manifest>, above <application> (not inside <application>).
Before (typical RN app):
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"
...>
...
</application>
</manifest>After (paste these two blocks):
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Voice search: required -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<queries>
<intent>
<action android:name="android.speech.RecognitionService" />
</intent>
</queries>
<application
android:name=".MainApplication"
...>
...
</application>
</manifest>| What you paste | Why |
|---|---|
| RECORD_AUDIO | Microphone (also requested at runtime) |
| <queries> + RecognitionService | Required on Android 11+; without it Voice.isAvailable() is often false |
Skip a line if it is already present. The library manifest also declares both; keep them in the app file so Play / merger issues do not drop them.
iOS
File to edit:
ios/<YourAppName>/Info.plistExample: if the Xcode project is MyApp, the path is usually ios/MyApp/Info.plist.
Open that plist and paste both keys inside the top-level <dict> (same level as other keys like CFBundleName). Use non-empty strings.
Paste:
<key>NSMicrophoneUsageDescription</key>
<string>Microphone access is used for voice search.</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Speech recognition converts your voice into search text.</string>iOS shows two prompts: microphone, then speech recognition. These keys do not merge from the library — the app Info.plist is required.
Runtime (optional)
No file to edit. Call this in JS if you want to request permissions before opening the mic:
import { Voice } from 'react-native-voice-search';
const permission = await Voice.requestPermissions();
if (!permission.granted) {
// permission.microphone / permission.speech:
// 'granted' | 'denied' | 'blocked' | 'unavailable'
}VoiceSearch also requests permissions when the mic is tapped.
Usage
Use in any screen / component file in your app (for example src/screens/SearchScreen.tsx):
import { useState } from 'react';
import { VoiceSearch } from 'react-native-voice-search';
export const SearchScreen = () => {
const [query, setQuery] = useState('');
return (
<VoiceSearch
value={query}
onChangeText={setQuery}
onSearch={(text) => {
// Call your API / filter list here
fetchResults(text);
}}
placeholder="Search leads"
debounceDelay={400}
/>
);
};With errors, locale, and styles
<VoiceSearch
value={query}
onChangeText={setQuery}
onSearch={fetchResults}
placeholder="Search leads"
debounceDelay={400}
autoHandleErrors={false}
onVoiceError={(error) => {
// Toast / i18n Alert
console.warn(error.code, error.message);
}}
voiceOptions={{ locale: 'en-IN' }}
containerStyle={{ borderRadius: 12 }}
/>Typing vs voice → when search runs
| Action | Updates text (onChangeText) | Calls onSearch |
|---|---|---|
| Typing | Yes | Yes, after debounceDelay |
| Speaking (partial) | Yes | No |
| Speaking finished | Yes | Yes |
| Keyboard Search / Done | — | Yes |
| Tap mic again to cancel | May restore previous text | No |
Use onChangeText to keep UI in sync. Use onSearch for the real API call.
API
VoiceSearch
Search field + mic. Explicit props (not full TextInputProps).
<VoiceSearch
value={query}
onChangeText={setQuery}
onSearch={searchProducts}
placeholder="Search products..."
placeholderTextColor="#94A3B8"
debounceDelay={400}
label="Search products"
showSearchIcon
showVoiceIcon
containerStyle={styles.bar}
inputStyle={styles.input}
renderSearchIcon={({ color }) => <MySearchIcon color={color} />}
renderVoiceIcon={({ color, listening }) => (
<MyMicIcon color={color} active={listening} />
)}
voiceOptions={{ locale: 'en-IN', silenceTimeoutMs: 400 }}
/>Icon priority: render* → searchIcon / voiceIcon → package defaults (DefaultSearchIcon / DefaultVoiceIcon).
Voice (headless)
Use when you need speech without the search UI.
import { Voice } from 'react-native-voice-search';
const sub = Voice.addListener('result', ({ transcript, isFinal }) => {
console.log(transcript, isFinal);
});
await Voice.requestPermissions();
await Voice.start({ locale: 'en-IN', interimResults: true });
await Voice.stop(); // or Voice.cancel()
await Voice.destroy();
sub.remove();Events: start · result · error · end · availabilityChange
Cancellation emits end with reason: 'cancelled' — not an error.
useVoice
import { useVoice } from 'react-native-voice-search';
const { state, transcript, error, start, stop, cancel } = useVoice();VoiceState: idle | starting | listening | processing | ended | error
Props
Text & search
| Prop | Type | Default | When to use |
|---|---|---|---|
| value | string | — | Controlled text (recommended) |
| defaultValue | string | — | Uncontrolled starting text (rare) |
| onChangeText | (text) => void | — | Keep React state in sync |
| onSearch | (query) => void | — | Run your API / filter |
| debounceDelay | number | 400 | Wait after typing before onSearch. 0 = every change |
| onSubmitEditing | TextInput handler | — | Extra work on keyboard Search/Done (analytics, navigate, dismiss keyboard). Search itself already runs via onSearch |
Keyboard & field
| Prop | Type | Default | Notes |
|---|---|---|---|
| placeholder | string | "Search" | Hint text |
| placeholderTextColor | string | #94A3B8 | Hint color |
| editable | boolean | true | Disables typing + mic when false |
| autoFocus | boolean | false | Focus on mount |
| returnKeyType | RN type | "search" | Keyboard return key label |
| keyboardType | RN type | — | Usually leave default |
| maxLength | number | — | Max characters |
| label | string | — | Title above the field |
| labelStyle | text style | — | Style the label |
Look & layout
| Prop | Styles… |
|---|---|
| style | Outer wrapper |
| containerStyle | Search bar row (border, height, radius) — most common |
| inputStyle | Text inside the field |
| searchIconStyle | Left icon slot |
| voiceIconStyle | Mic icon slot |
| voiceButtonStyle | Mic pressable |
There is no colors prop — use style props and/or render*Icon.
Icons
| Prop | Notes |
|---|---|
| showSearchIcon / showVoiceIcon | Default true |
| searchIcon / voiceIcon | React node or image source |
| renderSearchIcon | ({ color }) => ReactNode |
| renderVoiceIcon | ({ state, listening, error, color }) => ReactNode |
Voice callbacks & errors
| Prop | Notes |
|---|---|
| voiceOptions | See Voice options |
| onVoiceStateChange | Mic state for analytics / custom UI |
| onVoiceResult | Raw { transcript, isFinal } (optional if you use value + onSearch) |
| onVoiceError | Your Toast / i18n for important errors. Wins over package Alert |
| autoHandleErrors | Default true. Set false when you use onVoiceError |
Transient codes (busy, no-speech, timeout, …) are swallowed so the UI stays calm. onVoiceError is for permission / unavailable-style failures.
onSubmitEditing is only for side effects beyond search:
<VoiceSearch
value={query}
onChangeText={setQuery}
onSearch={fetchResults}
returnKeyType="search"
onSubmitEditing={() => {
analytics.track('search_submit_keyboard');
Keyboard.dismiss();
}}
/>Voice options
Optional. Omit if device language and defaults are fine.
| Option | Default | Meaning |
|---|---|---|
| locale | device locale | BCP-47, e.g. en-IN, hi-IN |
| interimResults | true | Live text while speaking |
| continuous | false | Best-effort keep listening |
| preferOnDevice | false | Prefer on-device recognizer; fails if unavailable |
| silenceTimeoutMs | 400 | Stop after this much silence. 0 = no auto-stop on silence |
voiceOptions={{
locale: 'en-IN', // Indian English (not the phone language)
interimResults: true, // "red" → "red shoes" while speaking
silenceTimeoutMs: 400, // stop ~400ms after user goes quiet
}}Or only what you need: voiceOptions={{ locale: 'hi-IN' }}.
Errors
type VoiceError = {
code: string;
message: string;
platform?: 'android' | 'ios';
nativeCode?: string; // diagnostics only — do not branch on this
};| Code | Typical cause |
|---|---|
| microphone-permission-denied | Mic denied / missing RECORD_AUDIO |
| speech-permission-denied | iOS speech permission denied |
| permission-denied | Generic permission failure |
| unavailable | No recognizer / service |
| service-unavailable | Recognition service failed |
| no-speech | Nothing matched |
| network | Network / transport failure |
| timeout | No speech / iOS session cap |
| busy | Android recognizer busy |
| audio | Recording / audio engine failed |
| locale-unsupported | Locale missing or not downloaded |
| native | Other native failure |
| module-unavailable | TurboModule missing / not linked |
Cancellation is not an error → listen for end with reason: 'cancelled'.
Platform notes
Unified JS API; engines differ.
Android
- Ends after silence for normal (
continuous={false}) utterances. continuousrestarts after a result (may hit busy; module retries).- Android 11+ needs the RecognitionService
<queries>entry. preferOnDeviceuses on-device recognizer on API 31+ when available.ERROR_CLIENTafter cancel is swallowed.
iOS
- Does not reliably stop on silence — library uses
silenceTimeoutMs. - Session capped ~60s; library stops around 55s.
- Needs mic and speech permission.
- Default path may send audio to Apple;
preferOnDeviceopts into on-device. - Backgrounding cancels recognition (does not resume).
Out of scope: wake words, intent parsing, custom vocab, file transcription, shipped ML models, Old Architecture.
Troubleshooting
| Symptom | Fix |
|---|---|
| Android isAvailable() false on API 30+ | Add RecognitionService <queries> in android/app/src/main/AndroidManifest.xml |
| iOS crash / blocked recognition | Add both usage keys in ios/<YourAppName>/Info.plist (non-empty) |
| Listening never ends on iOS | Rely on silenceTimeoutMs or tap mic to stop |
| Wrong language | Set voiceOptions.locale |
| Module missing | Confirm New Arch + rebuild after install |
destroy() is for process lifetime teardown. Unmounting VoiceSearch cancels the session; it does not destroy the module.
Contributing
See CONTRIBUTING.md.
License
MIT
