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.
Cách hoạt động
Phần tiêu đề “Cách hoạt động”listen()trả kết quả khi người dùng nói xong. Không event, không state machine.onInterimđiền vào ô ngay khi đang nói, nên danh sách lọc trực tiếp.contextualStringscho bộ nhận dạng biết những tên có thể tìm.- Lỗi đi vào
catch, kèmcodeđể chuyển thành câu thông báo.
Dùng
Toàn bộ mã nguồn
Phần tiêu đề “Toàn bộ mã nguồn”Chính file này đang chạy trong điện thoại: trang đọc nó trực tiếp từ repo.
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 },});import { Ionicons } from '@expo/vector-icons';import { useSpeechVolume, type SpeechError, type SpeechErrorCode } from 'expo-stt';import { createContext, use, useEffect, useState, type ComponentProps, type ReactNode } from 'react';import { Animated, Linking, Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { useInsets } from './safeArea';
/** Parts the demo apps share. Each app brings its own layout, colors and logic. */
export type Locale = 'en-US' | 'vi-VN';export type IconName = ComponentProps<typeof Ionicons>['name'];
type Demo = { locale: Locale; setLocale: (locale: Locale) => void; close: () => void };
export const DemoContext = createContext<Demo>({ locale: 'en-US', setLocale() {}, close() {} });
export const useDemo = () => use(DemoContext);
/** Safe areas, a back button and the language switch. */export function Screen(props: { title: string; color: string; background: string; children: ReactNode }) { const { title, color, background, children } = props; const { locale, setLocale, close } = useDemo(); const { top, bottom, left, right } = useInsets(); const padding = { paddingTop: top, paddingBottom: bottom, paddingLeft: left, paddingRight: right }; return ( <View style={[styles.screen, { backgroundColor: background }, padding]}> <View style={styles.header}> <Pressable accessibilityRole="button" accessibilityLabel="All demos" hitSlop={10} onPress={close}> <Ionicons name="chevron-back" size={24} color={color} /> </Pressable> <Text accessibilityRole="header" style={[styles.title, { color }]}> {title} </Text> <Pressable accessibilityRole="button" accessibilityLabel={`Language: ${locale}`} hitSlop={10} onPress={() => setLocale(locale === 'en-US' ? 'vi-VN' : 'en-US')} style={[styles.locale, { borderColor: color }]} > <Text style={[styles.localeText, { color }]}>{locale.slice(0, 2).toUpperCase()}</Text> </Pressable> </View> {children} </View> );}
export function IconButton(props: { icon: IconName; label: string; color: string; background: string; size?: number; disabled?: boolean; onPress: () => void;}) { const { icon, label, color, background, size = 52, disabled, onPress } = props; return ( <Pressable accessibilityRole="button" accessibilityLabel={label} accessibilityState={{ disabled }} disabled={disabled} onPress={onPress} style={({ pressed }) => [ styles.round, { width: size, height: size, backgroundColor: background, opacity: disabled ? 0.35 : pressed ? 0.75 : 1, }, ]} > <Ionicons name={icon} size={size * 0.46} color={color} /> </Pressable> );}
/** A microphone button with a halo that follows the voice. */export function MicButton(props: { isActive: boolean; color: string; background: string; size?: number; onPress: () => void;}) { const { isActive, color, background, size = 72, onPress } = props; return ( <View style={styles.center}> {isActive && <Halo color={background} size={size} />} <IconButton icon={isActive ? 'stop' : 'mic'} label={isActive ? 'Stop listening' : 'Start listening'} color={color} background={background} size={size} onPress={onPress} /> </View> );}
// On its own, because the volume renders about 15 times per second.function Halo({ color, size }: { color: string; size: number }) { const scale = useSmoothVolume(); return ( <Animated.View style={[ styles.halo, { width: size, height: size, borderRadius: size / 2, backgroundColor: color, transform: [{ scale: scale.interpolate({ inputRange: [0, 1], outputRange: [1.12, 1.8] }) }], }, ]} /> );}
const BARS = [0.35, 0.6, 0.9, 0.5, 1, 0.7, 0.95, 0.45, 0.8, 0.55, 0.85, 0.4];
export function Waveform({ color, height = 36 }: { color: string; height?: number }) { const volume = useSmoothVolume(); return ( <View accessible={false} style={[styles.wave, { height }]}> {BARS.map((weight, index) => ( <Animated.View key={index} style={{ width: 4, height, borderRadius: 2, backgroundColor: color, transform: [{ scaleY: volume.interpolate({ inputRange: [0, 1], outputRange: [0.1, weight] }) }], }} /> ))} </View> );}
function useSmoothVolume() { const level = useSpeechVolume(); const [value] = useState(() => new Animated.Value(0)); useEffect(() => { Animated.timing(value, { toValue: level, duration: 80, useNativeDriver: Platform.OS !== 'web', }).start(); }, [level, value]); return value;}
/** What each error means to the user. `null` is not worth a message. */const MESSAGES: Record<SpeechErrorCode, string | null> = { 'not-allowed': 'The microphone is blocked. Allow it in the settings.', 'language-not-supported': 'This language is not available on this device.', 'no-speech': 'I did not hear anything. Try again.', network: 'Speech recognition needs a connection.', 'audio-capture': 'The microphone is not available.', busy: 'The microphone is already in use.', interrupted: 'Listening was interrupted.', 'service-unavailable': Platform.OS === 'web' ? 'This browser cannot recognize speech. Try Chrome, Edge or Firefox.' : 'This device cannot recognize speech.', aborted: null, unknown: 'Something went wrong. Try again.',};
export function ErrorNote({ error }: { error: SpeechError | null }) { const message = error && MESSAGES[error.code]; if (!message) return null; const canFix = error.code === 'not-allowed' && Platform.OS !== 'web'; return ( <View accessibilityLiveRegion="polite" style={styles.error}> <Ionicons name="alert-circle" size={18} color="#8a1c1c" /> <Text style={styles.errorText}>{message}</Text> {canFix && ( <Text accessibilityRole="link" style={styles.errorLink} onPress={() => void Linking.openSettings()}> Settings </Text> )} </View> );}
const styles = StyleSheet.create({ screen: { flex: 1 }, header: { flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 16, height: 56 }, title: { flex: 1, fontSize: 17, fontWeight: '700' }, locale: { borderWidth: 1.5, borderRadius: 8, paddingHorizontal: 8, paddingVertical: 3 }, localeText: { fontSize: 12, fontWeight: '700' }, center: { alignItems: 'center', justifyContent: 'center' }, round: { borderRadius: 999, alignItems: 'center', justifyContent: 'center' }, halo: { position: 'absolute', opacity: 0.22 }, wave: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 4 }, error: { flexDirection: 'row', alignItems: 'center', gap: 8, marginHorizontal: 16, marginVertical: 8, padding: 12, borderRadius: 12, backgroundColor: '#fde4e1', }, errorText: { flex: 1, color: '#8a1c1c', fontSize: 14 }, errorLink: { color: '#8a1c1c', fontWeight: '700' },});Xem trên GitHub: example/scenes/search.tsxXem trên GitHub: example/scenes/ui.tsx