forked from wangziqi/gongxue-base
feat: upgrade student vocabulary learning flow
This commit is contained in:
@@ -392,3 +392,127 @@
|
||||
word-break: break-all;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.vocabulary-page .student-topbar {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.vocabulary-modebar {
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.vocabulary-study {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.vocabulary-progress {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.vocabulary-progress-track {
|
||||
width: 100%;
|
||||
height: 12px;
|
||||
overflow: hidden;
|
||||
border-radius: 999px;
|
||||
background: #e2e8f0;
|
||||
}
|
||||
|
||||
.vocabulary-progress-fill {
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: #2563eb;
|
||||
transition: width 180ms ease;
|
||||
}
|
||||
|
||||
.vocabulary-card {
|
||||
min-height: 560px;
|
||||
padding: 32px;
|
||||
border: 1px solid #dbe3ee;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.vocabulary-card.revealed {
|
||||
border-color: #bfdbfe;
|
||||
background: #f8fbff;
|
||||
}
|
||||
|
||||
.vocabulary-word {
|
||||
display: block;
|
||||
margin-top: 36px;
|
||||
color: #0f172a;
|
||||
font-size: 64px;
|
||||
font-weight: 850;
|
||||
line-height: 1.05;
|
||||
text-align: center;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.vocabulary-phonetic {
|
||||
display: block;
|
||||
margin-top: 16px;
|
||||
color: #64748b;
|
||||
font-size: 28px;
|
||||
line-height: 1.3;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.vocabulary-card-actions {
|
||||
justify-content: center;
|
||||
margin-top: 26px;
|
||||
}
|
||||
|
||||
.vocabulary-answer {
|
||||
margin-top: 34px;
|
||||
padding: 24px;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.vocabulary-actions {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.vocabulary-word-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.vocabulary-word-chip {
|
||||
min-width: 0;
|
||||
padding: 18px;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.vocabulary-word-chip.active {
|
||||
border-color: #2563eb;
|
||||
background: #eff6ff;
|
||||
}
|
||||
|
||||
.vocabulary-word-chip.favorite {
|
||||
border-color: #f59e0b;
|
||||
}
|
||||
|
||||
.vocabulary-chip-word {
|
||||
display: block;
|
||||
color: #0f172a;
|
||||
font-size: 24px;
|
||||
font-weight: 820;
|
||||
line-height: 1.3;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.vocabulary-chip-meta {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
color: #94a3b8;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,62 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import Taro from '@tarojs/taro';
|
||||
import { Button, Text, View } from '@tarojs/components';
|
||||
import { loadVocabularyUnits, loadVocabularyWords, type VocabularyUnit } from '@/services/catalog';
|
||||
import { loadVocabularyReviewPlan, loadVocabularyStats, reviewVocabularyWord, toggleWordFavorite, type VocabularyWord } from '@/services/learning';
|
||||
import {
|
||||
loadFavoriteWords,
|
||||
loadVocabularyReviewPlan,
|
||||
loadVocabularyStats,
|
||||
reviewVocabularyWord,
|
||||
toggleWordFavorite,
|
||||
type VocabularyWord,
|
||||
} from '@/services/learning';
|
||||
import { playWordPronunciation, type AccentType } from '@/services/pronunciation';
|
||||
import { getStorage, removeStorage, setStorage } from '@/services/storage';
|
||||
import '../student.css';
|
||||
|
||||
type StudyMode = 'plan' | 'unit' | 'favorites';
|
||||
|
||||
type SessionStats = {
|
||||
known: number;
|
||||
unknown: number;
|
||||
};
|
||||
|
||||
function wordKey(word: VocabularyWord) {
|
||||
return word.wordId || word.id || word.word;
|
||||
}
|
||||
|
||||
function wordRecordId(word: VocabularyWord) {
|
||||
return word.wordId || word.id || '';
|
||||
}
|
||||
|
||||
function progressStorageKey(unitId: string, mode: StudyMode) {
|
||||
return `tiku:vocabulary:${unitId || 'all'}:${mode}:index`;
|
||||
}
|
||||
|
||||
function statNumber(stats: Record<string, unknown> | null, key: string) {
|
||||
const value = stats?.[key];
|
||||
return typeof value === 'number' ? value : Number(value || 0);
|
||||
}
|
||||
|
||||
function modeLabel(mode: StudyMode) {
|
||||
if (mode === 'favorites') return '收藏练习';
|
||||
if (mode === 'unit') return '单元学习';
|
||||
return '今日计划';
|
||||
}
|
||||
|
||||
export default function StudentVocabularyPage() {
|
||||
const [units, setUnits] = useState<VocabularyUnit[]>([]);
|
||||
const [unitId, setUnitId] = useState('');
|
||||
const [mode, setMode] = useState<StudyMode>('plan');
|
||||
const [words, setWords] = useState<VocabularyWord[]>([]);
|
||||
const [favoriteIds, setFavoriteIds] = useState<Record<string, boolean>>({});
|
||||
const [stats, setStats] = useState<Record<string, unknown> | null>(null);
|
||||
const [index, setIndex] = useState(0);
|
||||
const [showAnswer, setShowAnswer] = useState(false);
|
||||
const [completed, setCompleted] = useState(false);
|
||||
const [accent, setAccent] = useState<AccentType>('us');
|
||||
const [sessionStats, setSessionStats] = useState<SessionStats>({ known: 0, unknown: 0 });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
@@ -23,35 +71,135 @@ export default function StudentVocabularyPage() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!unitId) return;
|
||||
Promise.all([loadVocabularyReviewPlan(unitId), loadVocabularyWords(unitId), loadVocabularyStats(unitId)])
|
||||
.then(([plan, wordPayload, statPayload]) => {
|
||||
const planned = plan.item?.words || [];
|
||||
setWords(planned.length ? planned : wordPayload.items || []);
|
||||
setStats(statPayload.item || null);
|
||||
})
|
||||
.catch(nextError => setError(nextError instanceof Error ? nextError.message : '单词加载失败'));
|
||||
}, [unitId]);
|
||||
setLoading(true);
|
||||
setError('');
|
||||
setCompleted(false);
|
||||
setShowAnswer(false);
|
||||
setSessionStats({ known: 0, unknown: 0 });
|
||||
|
||||
async function mark(word: VocabularyWord, result: 'known' | 'unknown') {
|
||||
const wordId = word.wordId || word.id;
|
||||
if (!wordId) return;
|
||||
await reviewVocabularyWord(wordId, result).catch(nextError => setError(nextError instanceof Error ? nextError.message : '复习提交失败'));
|
||||
setWords(prev => prev.filter(item => (item.wordId || item.id) !== wordId));
|
||||
Promise.all([
|
||||
mode === 'favorites' ? loadFavoriteWords(unitId) : Promise.resolve({ items: [] as VocabularyWord[] }),
|
||||
mode !== 'favorites' ? loadVocabularyWords(unitId) : Promise.resolve({ items: [] as VocabularyWord[] }),
|
||||
mode === 'plan' ? loadVocabularyReviewPlan(unitId) : Promise.resolve({ item: { words: [] as VocabularyWord[] } }),
|
||||
loadFavoriteWords(unitId).catch(() => ({ items: [] as VocabularyWord[] })),
|
||||
loadVocabularyStats(unitId),
|
||||
])
|
||||
.then(([favoritePayload, wordPayload, planPayload, favoritesForStatus, statPayload]) => {
|
||||
const planned = planPayload.item?.words || [];
|
||||
const nextWords = mode === 'favorites'
|
||||
? favoritePayload.items || []
|
||||
: mode === 'unit'
|
||||
? wordPayload.items || []
|
||||
: planned.length
|
||||
? planned
|
||||
: wordPayload.items || [];
|
||||
const savedIndex = getStorage<number>(progressStorageKey(unitId, mode));
|
||||
setWords(nextWords);
|
||||
setFavoriteIds(Object.fromEntries((favoritesForStatus.items || []).map(item => wordRecordId(item)).filter(Boolean).map(id => [id, true])));
|
||||
setStats(statPayload.item || null);
|
||||
setIndex(typeof savedIndex === 'number' ? Math.min(savedIndex, Math.max(0, nextWords.length - 1)) : 0);
|
||||
})
|
||||
.catch(nextError => setError(nextError instanceof Error ? nextError.message : '单词加载失败'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [unitId, mode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!unitId || !words.length) return;
|
||||
setStorage(progressStorageKey(unitId, mode), index);
|
||||
}, [index, mode, unitId, words.length]);
|
||||
|
||||
const current = words[index] || null;
|
||||
const progressPercent = words.length ? Math.round(((Math.min(index + 1, words.length)) / words.length) * 100) : 0;
|
||||
const favoriteCurrent = current ? !!favoriteIds[wordRecordId(current)] : false;
|
||||
|
||||
const unitName = useMemo(() => units.find(item => item.id === unitId)?.name || '单词单元', [units, unitId]);
|
||||
|
||||
function resetPosition(nextMode = mode) {
|
||||
removeStorage(progressStorageKey(unitId, nextMode));
|
||||
setIndex(0);
|
||||
setShowAnswer(false);
|
||||
setCompleted(false);
|
||||
setSessionStats({ known: 0, unknown: 0 });
|
||||
}
|
||||
|
||||
async function favorite(word: VocabularyWord) {
|
||||
const wordId = word.wordId || word.id;
|
||||
if (!wordId) return;
|
||||
await toggleWordFavorite(wordId, true).catch(nextError => setError(nextError instanceof Error ? nextError.message : '收藏失败'));
|
||||
function previousWord() {
|
||||
setIndex(prev => Math.max(0, prev - 1));
|
||||
setShowAnswer(false);
|
||||
setCompleted(false);
|
||||
}
|
||||
|
||||
function nextWord() {
|
||||
if (index >= words.length - 1) {
|
||||
setCompleted(true);
|
||||
return;
|
||||
}
|
||||
setIndex(prev => Math.min(words.length - 1, prev + 1));
|
||||
setShowAnswer(false);
|
||||
}
|
||||
|
||||
async function mark(result: 'known' | 'unknown') {
|
||||
if (!current) return;
|
||||
const id = wordRecordId(current);
|
||||
if (!id) {
|
||||
setError('单词数据缺少 ID,无法提交复习结果');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await reviewVocabularyWord(id, result);
|
||||
setSessionStats(prev => ({
|
||||
known: prev.known + (result === 'known' ? 1 : 0),
|
||||
unknown: prev.unknown + (result === 'unknown' ? 1 : 0),
|
||||
}));
|
||||
if (mode === 'plan') {
|
||||
setWords(prev => prev.filter(item => wordKey(item) !== id));
|
||||
setIndex(prev => Math.min(prev, Math.max(0, words.length - 2)));
|
||||
} else {
|
||||
nextWord();
|
||||
}
|
||||
} catch (nextError) {
|
||||
setError(nextError instanceof Error ? nextError.message : '复习提交失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleFavorite() {
|
||||
if (!current) return;
|
||||
const id = wordRecordId(current);
|
||||
if (!id) {
|
||||
setError('单词数据缺少 ID,无法收藏');
|
||||
return;
|
||||
}
|
||||
const nextFavorite = !favoriteCurrent;
|
||||
try {
|
||||
const payload = await toggleWordFavorite(id, nextFavorite);
|
||||
setFavoriteIds(prev => ({ ...prev, [id]: payload.favorite }));
|
||||
if (mode === 'favorites' && !payload.favorite) {
|
||||
setWords(prev => prev.filter(item => wordKey(item) !== id));
|
||||
setIndex(prev => Math.min(prev, Math.max(0, words.length - 2)));
|
||||
}
|
||||
Taro.showToast({ title: payload.favorite ? '已收藏' : '已取消收藏', icon: 'success' });
|
||||
} catch (nextError) {
|
||||
setError(nextError instanceof Error ? nextError.message : '收藏操作失败');
|
||||
}
|
||||
}
|
||||
|
||||
function jumpToWord(targetIndex: number) {
|
||||
setIndex(Math.max(0, Math.min(words.length - 1, targetIndex)));
|
||||
setShowAnswer(false);
|
||||
setCompleted(false);
|
||||
}
|
||||
|
||||
async function playCurrent() {
|
||||
if (!current?.word) return;
|
||||
await playWordPronunciation(current.word, accent);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className='student-page'>
|
||||
<View className='student-page vocabulary-page'>
|
||||
<View className='student-topbar'>
|
||||
<View className='student-title-block'>
|
||||
<Text className='student-kicker'>Vocabulary</Text>
|
||||
<Text className='student-title'>背单词</Text>
|
||||
<Text className='student-subtitle'>每日计划、复习调度和掌握状态都由后端维护。</Text>
|
||||
<Text className='student-subtitle'>{unitName} · {modeLabel(mode)} · 进度由后端复习计划维护</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -63,33 +211,98 @@ export default function StudentVocabularyPage() {
|
||||
))}
|
||||
</View>
|
||||
|
||||
<View className='section-block'>
|
||||
<Text className='section-heading'>学习统计</Text>
|
||||
<View className='grid-two'>
|
||||
<View className='metric'><Text className='metric-value'>{String(stats?.masteredWords ?? 0)}</Text><Text className='metric-label'>已掌握</Text></View>
|
||||
<View className='metric'><Text className='metric-value'>{String(stats?.todayReviewed ?? 0)}</Text><Text className='metric-label'>今日复习</Text></View>
|
||||
</View>
|
||||
<View className='toolbar wrap vocabulary-modebar'>
|
||||
<Button className={`pill-button ${mode === 'plan' ? 'active' : ''}`} onClick={() => setMode('plan')}>今日计划</Button>
|
||||
<Button className={`pill-button ${mode === 'unit' ? 'active' : ''}`} onClick={() => setMode('unit')}>单元学习</Button>
|
||||
<Button className={`pill-button ${mode === 'favorites' ? 'active' : ''}`} onClick={() => setMode('favorites')}>收藏练习</Button>
|
||||
<Button className='secondary-button' onClick={() => resetPosition()}>重新开始</Button>
|
||||
</View>
|
||||
|
||||
<View className='section-block'>
|
||||
<Text className='section-heading'>今日单词</Text>
|
||||
<View className='list-stack'>
|
||||
{words.slice(0, 20).map(word => (
|
||||
<View className='list-row' key={word.wordId || word.id || word.word}>
|
||||
<Text className='row-main'>{word.word} {word.phonetic ? `/${word.phonetic}/` : ''}</Text>
|
||||
<Text className='row-meta'>{word.meaning || '暂无释义'}</Text>
|
||||
{word.example ? <Text className='row-meta'>{word.example}</Text> : null}
|
||||
<View className='toolbar'>
|
||||
<Button className='primary-button' onClick={() => mark(word, 'known')}>认识</Button>
|
||||
<Button className='secondary-button' onClick={() => mark(word, 'unknown')}>再记</Button>
|
||||
<Button className='secondary-button' onClick={() => favorite(word)}>收藏</Button>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
{!words.length ? <View className='empty-state'>当前单元暂无待学习单词。</View> : null}
|
||||
{error ? <Text className='error-text'>{error}</Text> : null}
|
||||
<View className='grid-two section-block'>
|
||||
<View className='metric'><Text className='metric-value'>{String(statNumber(stats, 'masteredWords'))}</Text><Text className='metric-label'>已掌握</Text></View>
|
||||
<View className='metric'><Text className='metric-value'>{String(statNumber(stats, 'todayReviewed'))}</Text><Text className='metric-label'>今日复习</Text></View>
|
||||
</View>
|
||||
|
||||
{loading ? <View className='empty-state section-block'>单词加载中...</View> : null}
|
||||
|
||||
{!loading && current && !completed ? (
|
||||
<View className='vocabulary-study section-block'>
|
||||
<View className='vocabulary-progress'>
|
||||
<Text className='row-meta'>{index + 1}/{words.length} · {progressPercent}%</Text>
|
||||
<View className='vocabulary-progress-track'><View className='vocabulary-progress-fill' style={{ width: `${progressPercent}%` }} /></View>
|
||||
</View>
|
||||
|
||||
<View className={`vocabulary-card ${showAnswer ? 'revealed' : ''}`} onClick={() => setShowAnswer(prev => !prev)}>
|
||||
<View className='amount-row'>
|
||||
<Text className='status-badge'>{current.dueLevel || current.status || modeLabel(mode)}</Text>
|
||||
<Text className='status-badge'>{favoriteCurrent ? '已收藏' : '未收藏'}</Text>
|
||||
</View>
|
||||
<Text className='vocabulary-word'>{current.word}</Text>
|
||||
{current.phonetic ? <Text className='vocabulary-phonetic'>/{current.phonetic}/</Text> : null}
|
||||
<View className='toolbar wrap vocabulary-card-actions'>
|
||||
<Button className='secondary-button' onClick={(event) => { event.stopPropagation(); void playCurrent(); }}>发音</Button>
|
||||
<Button className='secondary-button' onClick={(event) => { event.stopPropagation(); setAccent(prev => (prev === 'us' ? 'uk' : 'us')); }}>{accent === 'us' ? '美音' : '英音'}</Button>
|
||||
<Button className='secondary-button' onClick={(event) => { event.stopPropagation(); void toggleFavorite(); }}>{favoriteCurrent ? '取消收藏' : '收藏'}</Button>
|
||||
</View>
|
||||
<View className='vocabulary-answer'>
|
||||
{showAnswer ? (
|
||||
<>
|
||||
<Text className='row-main'>{current.meaning || '暂无释义'}</Text>
|
||||
{current.example ? <Text className='row-meta'>{current.example}</Text> : null}
|
||||
{current.exampleTranslation ? <Text className='row-meta'>{current.exampleTranslation}</Text> : null}
|
||||
</>
|
||||
) : (
|
||||
<Text className='row-meta'>点击卡片查看释义和例句</Text>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className='toolbar wrap vocabulary-actions'>
|
||||
<Button className='secondary-button' onClick={previousWord}>上一个</Button>
|
||||
<Button className='danger-button' onClick={() => mark('unknown')}>再记</Button>
|
||||
<Button className='primary-button' onClick={() => mark('known')}>认识</Button>
|
||||
<Button className='secondary-button' onClick={nextWord}>下一个</Button>
|
||||
</View>
|
||||
|
||||
<View className='grid-two section-block'>
|
||||
<View className='metric'><Text className='metric-value'>{String(sessionStats.known)}</Text><Text className='metric-label'>本次认识</Text></View>
|
||||
<View className='metric'><Text className='metric-value'>{String(sessionStats.unknown)}</Text><Text className='metric-label'>本次再记</Text></View>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{!loading && (completed || !words.length) ? (
|
||||
<View className='report-panel section-block'>
|
||||
<Text className='metric-value'>{words.length ? '本组已完成' : '暂无单词'}</Text>
|
||||
<Text className='metric-label'>
|
||||
{mode === 'favorites' && !words.length ? '当前单元还没有收藏单词。' : '可以切换模式或重新开始本单元学习。'}
|
||||
</Text>
|
||||
<View className='toolbar wrap checkout-actions'>
|
||||
<Button className='primary-button' onClick={() => resetPosition()}>重新开始</Button>
|
||||
<Button className='secondary-button' onClick={() => setMode(mode === 'plan' ? 'unit' : 'plan')}>切换模式</Button>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{words.length ? (
|
||||
<View className='section-block'>
|
||||
<Text className='section-heading'>单词列表</Text>
|
||||
<View className='vocabulary-word-grid'>
|
||||
{words.map((item, itemIndex) => (
|
||||
<View
|
||||
className={`vocabulary-word-chip ${itemIndex === index ? 'active' : ''} ${favoriteIds[wordRecordId(item)] ? 'favorite' : ''}`}
|
||||
key={wordKey(item)}
|
||||
onClick={() => jumpToWord(itemIndex)}
|
||||
>
|
||||
<Text className='vocabulary-chip-word'>{item.word}</Text>
|
||||
<Text className='vocabulary-chip-meta'>{itemIndex + 1}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{error ? <Text className='error-text'>{error}</Text> : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -161,6 +161,8 @@ export interface VocabularyWord {
|
||||
difficulty?: string | null;
|
||||
status?: string;
|
||||
dueLevel?: string;
|
||||
favoritedAt?: string | null;
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
export async function createPracticeSession(body: {
|
||||
@@ -281,6 +283,12 @@ export async function toggleWordFavorite(wordId: string, favorite: boolean) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadFavoriteWords(unitId?: string, limit = 500) {
|
||||
return apiRequest<{ items?: VocabularyWord[] }>('/api/learning/vocabulary/favorites', {
|
||||
query: { unitId, limit },
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadVocabularyStats(unitId?: string) {
|
||||
return apiRequest<{ item?: Record<string, unknown> }>('/api/learning/vocabulary/stats', { query: { unitId } });
|
||||
}
|
||||
|
||||
97
apps/taro/src/services/pronunciation.ts
Normal file
97
apps/taro/src/services/pronunciation.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import Taro from '@tarojs/taro';
|
||||
|
||||
export type AccentType = 'us' | 'uk';
|
||||
|
||||
const YOUDAO_TYPE: Record<AccentType, number> = {
|
||||
us: 1,
|
||||
uk: 2,
|
||||
};
|
||||
|
||||
let currentAudio: HTMLAudioElement | null = null;
|
||||
let currentInnerAudio: Taro.InnerAudioContext | null = null;
|
||||
|
||||
function pronunciationUrl(word: string, accent: AccentType) {
|
||||
return `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(word)}&type=${YOUDAO_TYPE[accent] || 1}`;
|
||||
}
|
||||
|
||||
function stopCurrentAudio() {
|
||||
try {
|
||||
if (currentAudio) {
|
||||
currentAudio.pause();
|
||||
currentAudio.src = '';
|
||||
currentAudio = null;
|
||||
}
|
||||
} catch (_error) {
|
||||
// ignore playback cleanup errors
|
||||
}
|
||||
try {
|
||||
if (currentInnerAudio) {
|
||||
currentInnerAudio.stop();
|
||||
currentInnerAudio.destroy();
|
||||
currentInnerAudio = null;
|
||||
}
|
||||
} catch (_error) {
|
||||
// ignore playback cleanup errors
|
||||
}
|
||||
try {
|
||||
if (typeof window !== 'undefined' && 'speechSynthesis' in window) {
|
||||
window.speechSynthesis.cancel();
|
||||
}
|
||||
} catch (_error) {
|
||||
// ignore unsupported runtime
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackSpeech(word: string, accent: AccentType) {
|
||||
if (typeof window === 'undefined' || !('speechSynthesis' in window)) return false;
|
||||
try {
|
||||
const utterance = new SpeechSynthesisUtterance(word);
|
||||
utterance.lang = accent === 'uk' ? 'en-GB' : 'en-US';
|
||||
utterance.rate = 0.86;
|
||||
window.speechSynthesis.speak(utterance);
|
||||
return true;
|
||||
} catch (_error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function playWordPronunciation(word: string, accent: AccentType = 'us') {
|
||||
const text = word.trim();
|
||||
if (!text) return;
|
||||
stopCurrentAudio();
|
||||
|
||||
const url = pronunciationUrl(text, accent);
|
||||
|
||||
if (process.env.TARO_ENV === 'h5' && typeof Audio !== 'undefined') {
|
||||
try {
|
||||
const audio = new Audio(url);
|
||||
audio.preload = 'auto';
|
||||
currentAudio = audio;
|
||||
audio.onerror = () => {
|
||||
currentAudio = null;
|
||||
fallbackSpeech(text, accent);
|
||||
};
|
||||
await audio.play();
|
||||
return;
|
||||
} catch (_error) {
|
||||
if (fallbackSpeech(text, accent)) return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const audio = Taro.createInnerAudioContext();
|
||||
currentInnerAudio = audio;
|
||||
audio.src = url;
|
||||
audio.autoplay = true;
|
||||
audio.onEnded(() => {
|
||||
if (currentInnerAudio === audio) currentInnerAudio = null;
|
||||
audio.destroy();
|
||||
});
|
||||
audio.onError(() => {
|
||||
if (currentInnerAudio === audio) currentInnerAudio = null;
|
||||
audio.destroy();
|
||||
});
|
||||
} catch (_error) {
|
||||
Taro.showToast({ title: '当前环境暂不支持发音', icon: 'none' });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user