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

Ra lệnh bằng giọng nói

Nhà thông minh: thử lần lượt các phương án cho tới khi có một câu lệnh hợp lệ.

Demo chạy thật, cần micro.Mở toàn màn hình ↗
  1. maxAlternatives: 5 trả về các phương án mà bộ nhận dạng cân nhắc. Phương án đầu tiên hợp lệ được chọn.
  2. silenceTimeout: 800 để phản hồi nhanh, vì câu lệnh không có khoảng ngắt.
  3. continuous nhận hết lệnh này tới lệnh khác: onResult chạy một lần mỗi câu.
  4. contextualStrings ưu tiên các từ trong bộ lệnh.

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/commands.tsx
import { Ionicons } from '@expo/vector-icons';
import { useSpeechRecognition } from 'expo-stt';
import { useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { ErrorNote, MicButton, Screen, useDemo, type IconName, type Locale } from './ui';
const LIME = '#c6f24e';
const ROOMS = ['kitchen', 'bedroom', 'fan', 'music'] as const;
type Room = (typeof ROOMS)[number];
const ICONS: Record<Room, IconName> = {
kitchen: 'bulb',
bedroom: 'bed',
fan: 'leaf',
music: 'musical-notes',
};
const WORDS: Record<
Locale,
{ on: string; off: string; all: string; rooms: Record<Room, string>; try: string }
> = {
'en-US': {
on: 'on',
off: 'off',
all: 'everything',
rooms: { kitchen: 'kitchen', bedroom: 'bedroom', fan: 'fan', music: 'music' },
try: '“Turn on the kitchen”, “everything off”',
},
'vi-VN': {
on: 'bật',
off: 'tắt',
all: 'tất cả',
rooms: { kitchen: 'bếp', bedroom: 'phòng ngủ', fan: 'quạt', music: 'nhạc' },
try: '“Bật đèn bếp”, “tắt tất cả”',
},
};
type Command = { rooms: Room[]; isOn: boolean };
function parse(text: string, locale: Locale): Command | null {
const words = WORDS[locale];
// Whole words only: "on" is not in "bonfire".
const padded = ` ${text
.toLowerCase()
.normalize('NFC')
.replace(/[^\p{L}\p{N}]+/gu, ' ')} `;
const has = (word: string) => padded.includes(` ${word} `);
const rooms = ROOMS.filter((room) => has(words.all) || has(words.rooms[room]));
if (rooms.length === 0 || has(words.on) === has(words.off)) return null;
return { rooms, isOn: has(words.on) };
}
/** Voice commands: the first alternative that makes sense wins. */
export function Commands() {
const { locale } = useDemo();
const words = WORDS[locale];
const [isOn, setIsOn] = useState<Record<Room, boolean>>({
kitchen: false,
bedroom: true,
fan: false,
music: false,
});
const [feedback, setFeedback] = useState('');
const speech = useSpeechRecognition({
locale,
continuous: true,
maxAlternatives: 5,
// A command is short: do not wait long for more.
silenceTimeout: 800,
punctuation: false,
contextualStrings: [words.on, words.off, words.all, ...Object.values(words.rooms)],
onResult: ({ transcript, alternatives }) => {
const command = alternatives.map((text) => parse(text, locale)).find((found) => found !== null);
setFeedback(command ? `✓ ${transcript}` : `? ${transcript}`);
if (!command) return;
setIsOn((previous) => ({
...previous,
...Object.fromEntries(command.rooms.map((room) => [room, command.isOn])),
}));
},
});
return (
<Screen title="Voice commands" color="#f4f7ec" background="#14170f">
<View style={styles.grid}>
{ROOMS.map((room) => (
<Pressable
key={room}
accessibilityRole="switch"
accessibilityLabel={words.rooms[room]}
accessibilityState={{ checked: isOn[room] }}
onPress={() => setIsOn({ ...isOn, [room]: !isOn[room] })}
style={[styles.tile, isOn[room] && styles.tileOn]}
>
<Ionicons name={ICONS[room]} size={30} color={isOn[room] ? '#14170f' : '#8d947d'} />
<View>
<Text style={[styles.room, isOn[room] && styles.dark]}>{words.rooms[room]}</Text>
<Text style={[styles.state, isOn[room] && styles.dark]}>
{isOn[room] ? words.on : words.off}
</Text>
</View>
</Pressable>
))}
</View>
<ErrorNote error={speech.error} />
<View style={styles.dock}>
<Text accessibilityLiveRegion="polite" style={styles.heard}>
{speech.interimTranscript || feedback || (speech.isActive ? 'Listening…' : 'Tap, then say')}
</Text>
<Text style={styles.try}>{words.try}</Text>
<MicButton
isActive={speech.isActive}
color="#14170f"
background={LIME}
onPress={() => void speech.toggle()}
/>
</View>
</Screen>
);
}
const styles = StyleSheet.create({
grid: { flexDirection: 'row', flexWrap: 'wrap', gap: 12, padding: 16 },
tile: {
flexGrow: 1,
flexBasis: '45%',
height: 150,
padding: 18,
borderRadius: 26,
justifyContent: 'space-between',
backgroundColor: '#23281b',
},
tileOn: { backgroundColor: LIME },
room: { color: '#f4f7ec', fontSize: 19, fontWeight: '700', textTransform: 'capitalize' },
state: { color: '#a9b196', fontSize: 14, textTransform: 'capitalize' },
dark: { color: '#14170f' },
dock: {
flex: 1,
alignItems: 'center',
justifyContent: 'flex-end',
gap: 12,
padding: 20,
paddingBottom: 36,
},
heard: { color: '#f4f7ec', fontSize: 20, fontWeight: '600', textAlign: 'center' },
try: { color: '#a9b196', fontSize: 14, marginBottom: 18, textAlign: 'center' },
});