Skip to content

Voice search

One phrase, one await: the result of listen() goes into the search field.

Live demo, needs a microphone.Open full screen ↗
  1. listen() resolves when the user stops talking. No events, no state machine.
  2. onInterim fills the field while the user is speaking, so the list filters live.
  3. contextualStrings tells the recognizer which names can be found.
  4. Failures arrive in catch, with a code to translate into words.

Uses

This file is what runs in the phone: the page reads it from the repository.

example/scenes/search.tsx
import { Ionicons } from '@expo/vector-icons';
import { listen, SpeechError, stop } from 'expo-stt';
import { useState } from 'react';
import { FlatList, StyleSheet, Text, TextInput, View } from 'react-native';
import { ErrorNote, IconButton, Screen, useDemo, type Locale } from './ui';
const GREEN = '#0f5c3f';
const DISHES: Record<Locale, [emoji: string, name: string, minutes: number][]> = {
'en-US': [
['🍜', 'Beef noodle soup', 40],
['🥗', 'Green papaya salad', 15],
['🍲', 'Pumpkin soup', 30],
['🍝', 'Mushroom pasta', 25],
['🍛', 'Chicken curry', 45],
['🥞', 'Banana pancakes', 20],
['🍚', 'Egg fried rice', 15],
['🐟', 'Grilled salmon', 25],
],
'vi-VN': [
['🍜', 'Phở bò', 40],
['🥗', 'Gỏi đu đủ', 15],
['🍲', 'Canh bí đỏ', 30],
['🍝', 'Mì xào nấm', 25],
['🍛', 'Cà ri gà', 45],
['🥞', 'Bánh chuối', 20],
['🍚', 'Cơm chiên trứng', 15],
['🐟', 'Cá hồi nướng', 25],
],
};
/** "Phở bò." and "pho bo" are the same search. */
const normalize = (text: string) =>
text
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/đ/g, 'd')
.replace(/[^\p{L}\p{N} ]/gu, '')
.trim();
/** Voice search: one phrase, one await. */
export function Search() {
const { locale } = useDemo();
const [query, setQuery] = useState('');
const [isListening, setIsListening] = useState(false);
const [error, setError] = useState<SpeechError | null>(null);
const dishes = DISHES[locale];
const words = normalize(query).split(' ').filter(Boolean);
const matches = dishes.filter(([, name]) => words.every((word) => normalize(name).includes(word)));
const search = async () => {
setIsListening(true);
setError(null);
try {
const { transcript } = await listen({
locale,
punctuation: false,
// The recognizer favors the names that can be found.
contextualStrings: dishes.map(([, name]) => name),
onInterim: setQuery,
});
setQuery(transcript);
} catch (cause) {
setError(SpeechError.from(cause));
} finally {
setIsListening(false);
}
};
return (
<Screen title="Voice search" color={GREEN} background="#eef7f0">
<Text style={styles.heading}>What are we{'\n'}cooking today?</Text>
<View style={[styles.bar, isListening && styles.barActive]}>
<Ionicons name="search" size={20} color={GREEN} />
<TextInput
accessibilityLabel="Search dishes"
onChangeText={setQuery}
placeholder={isListening ? 'Listening…' : 'Type or speak'}
placeholderTextColor="#5f8a76"
style={styles.input}
value={query}
/>
{query !== '' && !isListening && (
<IconButton
icon="close"
label="Clear"
color={GREEN}
background="transparent"
size={40}
onPress={() => setQuery('')}
/>
)}
<IconButton
icon={isListening ? 'stop' : 'mic'}
label={isListening ? 'Stop listening' : 'Search by voice'}
color="#fff"
background={isListening ? '#d6503f' : GREEN}
size={44}
onPress={() => void (isListening ? stop() : search())}
/>
</View>
<ErrorNote error={error} />
<FlatList
contentContainerStyle={styles.list}
data={matches}
keyExtractor={([, name]) => name}
ListEmptyComponent={<Text style={styles.empty}>Nothing called “{query}”.</Text>}
renderItem={({ item: [emoji, name, minutes] }) => (
<View style={styles.dish}>
<Text style={styles.emoji}>{emoji}</Text>
<Text style={styles.name}>{name}</Text>
<Text style={styles.minutes}>{minutes} min</Text>
</View>
)}
/>
</Screen>
);
}
const styles = StyleSheet.create({
heading: { marginHorizontal: 20, marginVertical: 14, color: GREEN, fontSize: 32, fontWeight: '800' },
bar: {
flexDirection: 'row',
alignItems: 'center',
marginHorizontal: 16,
paddingLeft: 16,
paddingRight: 6,
height: 58,
borderRadius: 29,
borderWidth: 2,
borderColor: 'transparent',
backgroundColor: '#fff',
},
barActive: { borderColor: '#d6503f' },
// Without minWidth the input does not shrink on web.
input: { flex: 1, minWidth: 0, marginHorizontal: 10, color: '#123', fontSize: 17, height: 44 },
list: { padding: 16, gap: 10 },
dish: {
flexDirection: 'row',
alignItems: 'center',
gap: 14,
padding: 14,
borderRadius: 18,
backgroundColor: '#fff',
},
emoji: { fontSize: 28 },
name: { flex: 1, color: '#16352a', fontSize: 17, fontWeight: '600' },
minutes: { color: '#4d7664' },
empty: { padding: 30, textAlign: 'center', color: '#4d7664', fontSize: 16 },
});