Bỏ qua để đến nội dung

Tìm kiếm bằng giọng nói

Một câu, một await: kết quả của listen() được đưa vào ô tìm kiếm.

Demo chạy thật, cần micro.Mở toàn màn hình ↗
  1. listen() trả kết quả khi người dùng nói xong. Không event, không state machine.
  2. onInterim điền vào ô ngay khi đang nói, nên danh sách lọc trực tiếp.
  3. contextualStrings cho bộ nhận dạng biết những tên có thể tìm.
  4. Lỗi đi vào catch, kèm code để chuyển thành câu thông báo.

Dùng

Chính file này đang chạy trong điện thoại: trang đọc nó trực tiếp từ repo.

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 },
});