Commit
Add voice picking and speech callbacks to TTS
commit
9d5ae91
1 changed file with +33 and −2
modified client/src/tts.ts +33 −2
| @@ -1,7 +1,38 @@ | ||
| 1 | -export function speak(text: string): void { | |
| 1 | +export interface SpeakCallbacks { | |
| 2 | + onStart?: () => void | |
| 3 | + onEnd?: () => void | |
| 4 | +} | |
| 5 | + | |
| 6 | +function pickVoice(): SpeechSynthesisVoice | null { | |
| 7 | + const voices = window.speechSynthesis.getVoices() | |
| 8 | + let best: SpeechSynthesisVoice | null = null | |
| 9 | + let bestScore = 0 | |
| 10 | + for (const voice of voices) { | |
| 11 | + let score = 1 | |
| 12 | + if (voice.lang.toLowerCase().startsWith('en')) score += 2 | |
| 13 | + if (/natural/i.test(voice.name)) score += 4 | |
| 14 | + if (/online/i.test(voice.name)) score += 3 | |
| 15 | + if (/google/i.test(voice.name)) score += 2 | |
| 16 | + if (score > bestScore) { | |
| 17 | + bestScore = score | |
| 18 | + best = voice | |
| 19 | + } | |
| 20 | + } | |
| 21 | + return best | |
| 22 | +} | |
| 23 | + | |
| 24 | +export function speak(text: string, callbacks: SpeakCallbacks = {}): void { | |
| 2 | 25 | if (!('speechSynthesis' in window)) return |
| 3 | 26 | window.speechSynthesis.cancel() |
| 4 | - window.speechSynthesis.speak(new SpeechSynthesisUtterance(text)) | |
| 27 | + const utterance = new SpeechSynthesisUtterance(text) | |
| 28 | + const voice = pickVoice() | |
| 29 | + if (voice) utterance.voice = voice | |
| 30 | + utterance.rate = 1 | |
| 31 | + utterance.pitch = 1 | |
| 32 | + utterance.onstart = () => callbacks.onStart?.() | |
| 33 | + utterance.onend = () => callbacks.onEnd?.() | |
| 34 | + utterance.onerror = () => callbacks.onEnd?.() | |
| 35 | + window.speechSynthesis.speak(utterance) | |
| 5 | 36 | } |
| 6 | 37 | |
| 7 | 38 | export function stopSpeaking(): void { |