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

Playground

Mọi tuỳ chọn và mọi event, để xem thiết bị thực sự làm gì.

Demo chạy thật, cần micro.Mở toàn màn hình ↗
  1. addListener ghi lại event thô theo đúng thứ tự.
  2. getCapabilities() cho biết trước tuỳ chọn nào có tác dụng.
  3. Dùng để thử thiết bị, hoặc đính kèm log khi báo lỗi.

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/playground.tsx
import {
addListener,
getCapabilities,
getSupportedLocalesAsync,
useSpeechPermissions,
useSpeechRecognition,
} from 'expo-stt';
import { useEffect, useState } from 'react';
import { Platform, Pressable, ScrollView, StyleSheet, Switch, Text, View } from 'react-native';
import { ErrorNote, Screen, useDemo, Waveform } from './ui';
const CYAN = '#5ad1e6';
const FLAGS = ['continuous', 'interimResults', 'punctuation', 'requiresOnDeviceRecognition'] as const;
type Flags = Record<(typeof FLAGS)[number], boolean>;
// react-native-web has its own prop for the thumb of a switch that is on.
const WEB_SWITCH = Platform.OS === 'web' ? { activeThumbColor: '#fff' } : null;
const SILENCE = [800, 2000, 4000];
/** Every option and every event, to see what a device really does. */
export function Playground() {
const { locale } = useDemo();
const [permission, , refreshPermission] = useSpeechPermissions();
const [flags, setFlags] = useState<Flags>({
continuous: false,
interimResults: true,
punctuation: true,
requiresOnDeviceRecognition: false,
});
const [silenceTimeout, setSilenceTimeout] = useState(2000);
const [log, setLog] = useState<{ id: number; line: string }[]>([]);
const [capabilities] = useState(() => getCapabilities(locale));
const speech = useSpeechRecognition({ locale, silenceTimeout, maxAlternatives: 3, ...flags });
const append = (line: string) =>
setLog((lines) => [{ id: (lines[0]?.id ?? 0) + 1, line }, ...lines].slice(0, 50));
useEffect(() => {
const subscriptions = [
addListener('start', () => {
append('start');
// start() may have asked for it.
void refreshPermission();
}),
addListener('result', ({ transcript, isFinal, segment }) =>
append(`result #${segment} ${isFinal ? 'final' : 'interim'} “${transcript}”`),
),
addListener('error', ({ code, message }) => append(`error ${code}: ${message}`)),
addListener('end', ({ reason }) => append(`end ${reason}`)),
];
return () => subscriptions.forEach((subscription) => subscription.remove());
}, [refreshPermission]);
const listLocales = async () => {
const locales = await getSupportedLocalesAsync();
append(locales.length > 0 ? locales.join(' ') : 'locales unknown');
};
const buttons: [title: string, isEnabled: boolean, onPress: () => void][] = [
['Start', !speech.isActive, () => void speech.start()],
['Stop', speech.status === 'listening', () => void speech.stop()],
['Abort', speech.isActive, () => void speech.abort()],
['Locales', true, () => void listLocales()],
];
return (
<Screen title="Playground" color="#e6f3f6" background="#0d1b22">
<View style={styles.panel}>
{FLAGS.map((flag) => (
<View key={flag} style={styles.row}>
<Text style={styles.label}>{flag}</Text>
<Switch
accessibilityLabel={flag}
thumbColor={flags[flag] ? '#fff' : '#93b4bf'}
trackColor={{ true: CYAN, false: '#21414f' }}
{...WEB_SWITCH}
disabled={speech.isActive}
onValueChange={(value) => setFlags({ ...flags, [flag]: value })}
value={flags[flag]}
/>
</View>
))}
<View style={styles.row}>
<Text style={styles.label}>silenceTimeout</Text>
{SILENCE.map((value) => (
<Pressable
key={value}
accessibilityRole="radio"
accessibilityState={{ checked: value === silenceTimeout }}
hitSlop={6}
onPress={() => setSilenceTimeout(value)}
style={[styles.chip, value === silenceTimeout && styles.chipOn]}
>
<Text style={value === silenceTimeout ? styles.chipTextOn : styles.chipText}>{value}</Text>
</Pressable>
))}
</View>
<Text style={styles.facts}>
permission {permission?.status ?? '…'} ·{' '}
{Object.entries(capabilities)
.map(([name, value]) => `${name} ${value ? '✓' : '✗'}`)
.join(' · ')}
</Text>
</View>
<View style={styles.buttons}>
{buttons.map(([title, isEnabled, onPress]) => (
<Pressable
key={title}
accessibilityRole="button"
accessibilityState={{ disabled: !isEnabled }}
disabled={!isEnabled}
onPress={onPress}
style={[styles.button, !isEnabled && styles.disabled]}
>
<Text style={styles.buttonText}>{title}</Text>
</Pressable>
))}
</View>
<View style={styles.live}>
<View style={styles.row}>
<Text style={styles.status}>{speech.status}</Text>
<Waveform color={CYAN} height={22} />
</View>
<Text style={styles.transcript}>{speech.transcript || '…'}</Text>
</View>
<ErrorNote error={speech.error} />
<ScrollView contentContainerStyle={styles.log}>
{log.map(({ id, line }) => (
<Text key={id} style={styles.line}>
{line}
</Text>
))}
</ScrollView>
</Screen>
);
}
const styles = StyleSheet.create({
panel: { marginHorizontal: 16, padding: 14, gap: 4, borderRadius: 18, backgroundColor: '#152a34' },
row: { flexDirection: 'row', alignItems: 'center', gap: 8, minHeight: 36 },
label: { flex: 1, color: '#e6f3f6', fontSize: 14, fontFamily: 'monospace' },
chip: { paddingHorizontal: 10, paddingVertical: 5, borderRadius: 10, backgroundColor: '#21414f' },
chipOn: { backgroundColor: CYAN },
chipText: { color: '#e6f3f6', fontSize: 13 },
chipTextOn: { color: '#0d1b22', fontSize: 13, fontWeight: '700' },
facts: { color: '#93b4bf', fontSize: 12, lineHeight: 18, marginTop: 6 },
buttons: { flexDirection: 'row', gap: 8, padding: 16 },
button: { flex: 1, paddingVertical: 13, borderRadius: 14, alignItems: 'center', backgroundColor: CYAN },
disabled: { opacity: 0.35 },
buttonText: { color: '#0d1b22', fontWeight: '700' },
live: { marginHorizontal: 16, padding: 14, borderRadius: 18, backgroundColor: '#152a34' },
status: { flex: 1, color: CYAN, fontWeight: '700' },
transcript: { color: '#e6f3f6', fontSize: 18, lineHeight: 26 },
log: { padding: 16, gap: 4 },
line: { color: '#93b4bf', fontSize: 12, fontFamily: 'monospace' },
});