-
-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathSpeechQueue.cs
More file actions
272 lines (246 loc) · 8.38 KB
/
SpeechQueue.cs
File metadata and controls
272 lines (246 loc) · 8.38 KB
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Speech.Synthesis;
using System.Threading;
using System.Threading.Channels;
namespace BabySmash
{
internal sealed class SpeechQueue : IDisposable
{
private readonly Channel<SpeechItem> _channel;
private readonly Thread _workerThread;
private readonly CancellationTokenSource _cts = new();
private SpeechSynthesizer _synth;
private readonly Dictionary<string, InstalledVoice> _voiceCache = new();
private readonly object _voiceLock = new();
private readonly struct SpeechItem
{
public SpeechItem(string text, CultureInfo culture)
{
Text = text;
Culture = culture;
}
public string Text { get; }
public CultureInfo Culture { get; }
}
public SpeechQueue(int capacity = 5)
{
var options = new BoundedChannelOptions(capacity)
{
SingleReader = true,
SingleWriter = false,
FullMode = BoundedChannelFullMode.DropOldest
};
_channel = Channel.CreateBounded<SpeechItem>(options);
_workerThread = new Thread(WorkerLoop)
{
IsBackground = true
};
_workerThread.SetApartmentState(ApartmentState.STA);
_workerThread.Start();
}
public void Enqueue(string text, CultureInfo culture, bool priority = false)
{
if (string.IsNullOrWhiteSpace(text))
{
return;
}
if (priority)
{
// Make room for a high-priority utterance (e.g., a detected word).
while (_channel.Reader.TryRead(out _))
{
}
}
// Signal that new speech is pending (worker will cancel current speech)
_newItemPending = true;
_channel.Writer.TryWrite(new SpeechItem(text, culture));
}
private volatile bool _newItemPending;
private void WorkerLoop()
{
// SpeechSynthesizer is a COM object that requires STA thread
Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.STA,
"SpeechSynthesizer requires STA thread");
_synth = new SpeechSynthesizer
{
Rate = -1, // Slower for baby clarity
Volume = 100
};
try
{
var reader = _channel.Reader;
// Using blocking wait (not await) to ensure we stay on this STA thread.
// async/await could switch threads after await, breaking STA requirements.
while (reader.WaitToReadAsync(_cts.Token).AsTask().GetAwaiter().GetResult())
{
while (reader.TryRead(out var item))
{
SpeakItem(item);
}
}
}
catch (OperationCanceledException)
{
// Normal shutdown.
}
finally
{
_synth?.Dispose();
}
}
private void SpeakItem(SpeechItem item)
{
_newItemPending = false;
string textToSpeak = item.Text;
var voice = GetCachedVoice(item.Culture);
if (voice == null)
{
textToSpeak = "Unsupported Language";
}
else if (!voice.Enabled)
{
textToSpeak = "Voice Disabled";
}
else
{
try
{
_synth.SelectVoice(voice.VoiceInfo.Name);
}
catch
{
// Keep default voice.
}
}
try
{
// Use async speech so we can cancel if new input arrives
_synth.SpeakAsync(textToSpeak);
// Wait for speech to complete, but cancel if new item arrives
while (_synth.State == SynthesizerState.Speaking)
{
Thread.Sleep(50);
if (_newItemPending)
{
_synth.SpeakAsyncCancelAll();
break;
}
}
}
catch
{
// Swallow speech errors to keep the app responsive.
}
}
public void Dispose()
{
_cts.Cancel();
_channel.Writer.TryComplete();
}
private InstalledVoice GetCachedVoice(CultureInfo culture)
{
var key = culture.Name;
lock (_voiceLock)
{
if (_voiceCache.TryGetValue(key, out var cached))
{
return cached;
}
var voice = TryGetVoiceWithFallback(culture);
_voiceCache[key] = voice;
return voice;
}
}
private InstalledVoice TryGetVoiceWithFallback(CultureInfo culture)
{
// Try exact culture match (e.g., "es-MX")
var voice = _synth.GetInstalledVoices(culture).FirstOrDefault();
if (voice != null)
{
return voice;
}
// Try fallback from specific locale to base language (e.g., from "es-MX" to "es-ES")
if (culture.Name.Contains('-'))
{
string baseLanguage = culture.Name.Split('-')[0];
// Try common base language variants (es-ES, de-DE, etc.)
try
{
var baseCulture = new CultureInfo($"{baseLanguage}-{baseLanguage.ToUpper()}");
voice = _synth.GetInstalledVoices(baseCulture).FirstOrDefault();
if (voice != null)
{
return voice;
}
}
catch (CultureNotFoundException)
{
// Invalid culture, continue to next fallback
}
catch (ArgumentException)
{
// Invalid culture name format, continue to next fallback
}
// Try just the base language (e.g., "es")
try
{
var langOnlyCulture = new CultureInfo(baseLanguage);
voice = _synth.GetInstalledVoices(langOnlyCulture).FirstOrDefault();
if (voice != null)
{
return voice;
}
}
catch (CultureNotFoundException)
{
// Invalid culture, continue to next fallback
}
catch (ArgumentException)
{
// Invalid culture name format, continue to next fallback
}
}
// Final fallback to English
try
{
var enUsCulture = new CultureInfo("en-US");
voice = _synth.GetInstalledVoices(enUsCulture).FirstOrDefault();
if (voice != null)
{
return voice;
}
}
catch (CultureNotFoundException)
{
// If even en-US fails, try just "en"
}
catch (ArgumentException)
{
// Invalid culture name format, try just "en"
}
try
{
var enCulture = new CultureInfo("en");
voice = _synth.GetInstalledVoices(enCulture).FirstOrDefault();
if (voice != null)
{
return voice;
}
}
catch (CultureNotFoundException)
{
// All fallbacks failed
}
catch (ArgumentException)
{
// Invalid culture name format
}
// Last resort: return any available voice
return _synth.GetInstalledVoices().FirstOrDefault();
}
}
}