Spaces:
Running on Zero
Running on Zero
File size: 4,602 Bytes
d53374c a634105 d53374c 641b48b d53374c 78e83a2 d53374c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | 'use client';
/**
* Universal Indic Text-to-Speech Engine with strict de-duplication
* Priority 1: High-Fidelity Server-Side Audio Stream (/api/tts - gTTS Indic Engine)
* Priority 2: Native Web Speech API with explicit Indic voice resolution
*/
class UniversalIndicTTSEngine {
private currentAudio: HTMLAudioElement | null = null;
private synth: SpeechSynthesis | null = null;
private voices: SpeechSynthesisVoice[] = [];
private backendUrl: string = process.env.NEXT_PUBLIC_HTTP_BACKEND_URL || '';
private lastSpokenText: string = '';
private lastSpokenTimestamp: number = 0;
constructor() {
if (typeof window !== 'undefined') {
if ('speechSynthesis' in window) {
this.synth = window.speechSynthesis;
this.loadVoices();
if (this.synth.onvoiceschanged !== undefined) {
this.synth.onvoiceschanged = () => this.loadVoices();
}
}
}
}
private loadVoices() {
if (!this.synth) return;
this.voices = this.synth.getVoices();
}
public setBackendUrl(url: string) {
this.backendUrl = url;
}
public stop() {
// 1. Stop any HTML5 audio playback
if (this.currentAudio) {
this.currentAudio.pause();
this.currentAudio.currentTime = 0;
this.currentAudio = null;
}
// 2. Stop browser speech synthesis
if (this.synth) {
this.synth.cancel();
}
}
public async speak(
text: string,
langCode: string = 'en-IN',
onEnd?: () => void,
onError?: () => void,
force: boolean = false
) {
if (!text.trim()) return;
const trimmed = text.trim();
const now = Date.now();
// Prevent duplicate triggers of the exact same utterance within 3.5 seconds
if (!force && this.lastSpokenText === trimmed && now - this.lastSpokenTimestamp < 3500) {
return;
}
this.lastSpokenText = trimmed;
this.lastSpokenTimestamp = now;
this.stop();
// Strategy A: Server-side Indic TTS via /api/tts (Crystal clear Hindi, Tamil, Telugu, Marathi, etc.)
try {
const baseUrl = this.backendUrl ? this.backendUrl.replace(/\/$/, '') : '';
const res = await fetch(`${baseUrl}/api/tts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: trimmed,
language_code: langCode,
}),
});
if (res.ok) {
const audioBlob = await res.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
this.currentAudio = audio;
audio.onended = () => {
URL.revokeObjectURL(audioUrl);
this.currentAudio = null;
if (onEnd) onEnd();
};
audio.onerror = () => {
URL.revokeObjectURL(audioUrl);
this.currentAudio = null;
this.fallbackBrowserSpeech(trimmed, langCode, onEnd, onError);
};
await audio.play();
return;
}
} catch (e) {
console.warn('Server TTS unavailable, trying browser synthesis fallback:', e);
}
// Strategy B: Browser Web Speech API fallback
this.fallbackBrowserSpeech(trimmed, langCode, onEnd, onError);
}
private fallbackBrowserSpeech(
text: string,
langCode: string,
onEnd?: () => void,
onError?: () => void
) {
if (!this.synth) {
if (onError) onError();
return;
}
try {
if (this.synth.paused) {
this.synth.resume();
}
const utterance = new SpeechSynthesisUtterance(text);
if (this.voices.length === 0) {
this.loadVoices();
}
const primaryCode = langCode.toLowerCase().split('-')[0];
const matchingVoice = this.voices.find(
(v) =>
v.lang.toLowerCase().startsWith(primaryCode) ||
v.name.toLowerCase().includes(primaryCode) ||
v.name.toLowerCase().includes('india') ||
v.name.toLowerCase().includes('hindi')
);
if (matchingVoice) {
utterance.voice = matchingVoice;
utterance.lang = matchingVoice.lang;
} else {
utterance.lang = langCode;
}
utterance.rate = 1.0;
utterance.pitch = 1.0;
utterance.onend = () => {
if (onEnd) onEnd();
};
utterance.onerror = (e) => {
console.warn('Browser Speech warning:', e);
if (onError) onError();
};
this.synth.speak(utterance);
} catch (err) {
console.error('Browser TTS fallback error:', err);
if (onError) onError();
}
}
}
export const ttsEngine = new UniversalIndicTTSEngine();
|