Skip to content

Pronunciation

Words light up while you read them, then you get a score.

Live demo, needs a microphone.Open full screen ↗
  1. interimTranscript is compared with the sentence on every render: that is the live highlight.
  2. When the phrase is final, the alternative that fits best counts.
  3. punctuation: false leaves only words to compare.

Uses

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

example/scenes/practice.tsx
import { useSpeechRecognition } from 'expo-stt';
import { useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { ErrorNote, MicButton, Screen, useDemo, type Locale } from './ui';
const ORANGE = '#e8590c';
const SENTENCES: Record<Locale, string[]> = {
'en-US': [
'The quick brown fox jumps over the lazy dog',
'She sells sea shells by the sea shore',
'I would like a cup of tea with a little milk',
],
'vi-VN': ['Hôm nay trời đẹp quá', 'Lúa nếp là lúa nếp làng', 'Cho tôi một ly cà phê sữa đá'],
};
const toWords = (text: string) =>
text
.toLowerCase()
.normalize('NFC')
.replace(/[^\p{L}\p{N} ]/gu, '')
.split(' ')
.filter(Boolean);
/** Which words of the sentence were said, in order: the longest common subsequence. */
function match(expected: string[], spoken: string[]): boolean[] {
const length = expected.map(() => spoken.map(() => 0));
const at = (i: number, j: number) => length[i]?.[j] ?? 0;
for (let i = expected.length - 1; i >= 0; i--) {
for (let j = spoken.length - 1; j >= 0; j--) {
length[i][j] = expected[i] === spoken[j] ? at(i + 1, j + 1) + 1 : Math.max(at(i + 1, j), at(i, j + 1));
}
}
let j = 0;
return expected.map((word, i) => {
while (j < spoken.length && word !== spoken[j] && at(i, j + 1) === at(i, j)) j++;
const isSaid = j < spoken.length && word === spoken[j];
if (isSaid) j++;
return isSaid;
});
}
const score = (said: boolean[]) => Math.round((100 * said.filter(Boolean).length) / said.length);
/** Pronunciation practice: words light up while you read them. */
export function Practice() {
const { locale } = useDemo();
const [index, setIndex] = useState(0);
const [best, setBest] = useState<boolean[] | null>(null);
const sentence = SENTENCES[locale][index % SENTENCES[locale].length];
const words = sentence.split(' ');
const expected = toWords(sentence);
const speech = useSpeechRecognition({
locale,
punctuation: false,
maxAlternatives: 5,
// Be generous: the alternative that fits best counts.
onResult: ({ alternatives }) =>
setBest(
alternatives
.map((text) => match(expected, toWords(text)))
.reduce((left, right) => (score(right) > score(left) ? right : left)),
),
});
const said = best ?? match(expected, toWords(speech.interimTranscript));
const next = () => {
setIndex(index + 1);
setBest(null);
speech.reset();
};
const toggle = () => {
if (!speech.isActive) setBest(null);
void speech.toggle();
};
return (
<Screen title="Pronunciation" color="#4a1d05" background="#fff4ea">
<View style={styles.card}>
<Text style={styles.prompt}>Read aloud</Text>
<Text style={styles.sentence}>
{words.map((word, position) => (
<Text key={position}>
<Text style={said[position] ? styles.right : best ? styles.wrong : undefined}>{word}</Text>{' '}
</Text>
))}
</Text>
</View>
<View accessibilityLiveRegion="polite" style={styles.result}>
{best && (
<>
<Text style={styles.score}>{score(best)}%</Text>
<Text style={styles.verdict}>
{score(best) === 100 ? 'Perfect!' : score(best) >= 70 ? 'Almost there.' : 'Once more?'}
</Text>
</>
)}
</View>
<ErrorNote error={speech.error} />
<View style={styles.dock}>
<MicButton isActive={speech.isActive} color="#fff" background={ORANGE} onPress={toggle} />
<Pressable
accessibilityRole="button"
accessibilityState={{ disabled: speech.isActive }}
disabled={speech.isActive}
hitSlop={12}
onPress={next}
>
<Text style={[styles.next, speech.isActive && styles.disabled]}>Next sentence</Text>
</Pressable>
</View>
</Screen>
);
}
const styles = StyleSheet.create({
card: { margin: 16, padding: 24, borderRadius: 28, backgroundColor: '#fff' },
prompt: { color: '#a3480f', fontSize: 14, fontWeight: '700', marginBottom: 10 },
sentence: { color: '#4a1d05', fontSize: 30, lineHeight: 44, fontWeight: '700' },
right: { color: '#16803c' },
// Not by color alone.
wrong: { color: '#b3261e', textDecorationLine: 'underline' },
result: { flex: 1, alignItems: 'center', justifyContent: 'center' },
score: { color: ORANGE, fontSize: 72, fontWeight: '800' },
verdict: { color: '#4a1d05', fontSize: 18 },
dock: { alignItems: 'center', gap: 26, paddingBottom: 32 },
next: { color: '#a3480f', fontSize: 16, fontWeight: '700' },
disabled: { opacity: 0.4 },
});