-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnhancedAudioCaptureService.cs
More file actions
2567 lines (2232 loc) · 97.4 KB
/
EnhancedAudioCaptureService.cs
File metadata and controls
2567 lines (2232 loc) · 97.4 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Linq;
using System.Configuration;
using System.Speech.Recognition;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Collections.Generic;
using System.Diagnostics;
using NAudio.Wave;
using NAudio.CoreAudioApi;
using Newtonsoft.Json.Linq;
using Vosk;
namespace TimeTask
{
/// <summary>
/// 增强型智能语音监听服务
/// - 降低资源消耗 (16kHz 采样率)
/// - 只转文字,不保存音频
/// - 本地意图识别 + 任务草稿生成
/// - 静默运行,不打扰用户
/// </summary>
public sealed class EnhancedAudioCaptureService : IDisposable
{
private readonly object _lock = new object();
private readonly TimeSpan _silenceTimeout;
private readonly float _confidenceThreshold;
private readonly SpeechModelManager _speechModelManager;
private readonly Task<SpeechModelBootstrapResult> _modelBootstrapTask;
private readonly bool _autoAddVoiceTasks;
private readonly float _autoAddMinConfidence;
private readonly bool _useLlmForVoiceQuadrant;
private readonly bool _requireDraftConfirmation;
private readonly bool _conversationExtractEnabled;
private readonly TimeSpan _conversationWindow;
private readonly int _conversationMinTurns;
private DateTime _lastConversationExtract = DateTime.MinValue;
private readonly List<(DateTime ts, string text)> _conversationBuffer = new List<(DateTime, string)>();
private readonly SemaphoreSlim _llmSemaphore = new SemaphoreSlim(1, 1);
private LlmService _llmService;
private readonly SpeakerVerificationService _speakerService;
private readonly bool _speakerVerifyEnabled;
private readonly bool _speakerEnrollMode;
private readonly double _speakerThreshold;
private readonly double _speakerMinSeconds;
private bool _lastSpeakerVerified;
private DateTime _lastSpeakerVerifyTime = DateTime.MinValue;
private readonly List<byte> _speechBuffer = new List<byte>(16000 * 2 * 5);
private SpeechRecognitionEngine _recognizer;
private Model _voskModel;
private VoskRecognizer _voskRecognizer;
private bool _voskEnabled;
private bool _voskFormatWarningLogged;
private readonly bool _useStrictVoskGrammar;
private readonly bool _systemSpeechUseHints;
private readonly HashSet<string> _hintPhrases = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly string _asrProvider;
private readonly bool _funAsrEnabled;
private readonly bool _funAsrOnlyMode;
private string _funAsrPythonExe;
private readonly string _funAsrScriptPath;
private readonly string _funAsrModel;
private readonly string _funAsrDevice;
private readonly int _funAsrTimeoutSeconds;
private readonly int _funAsrWorkerStartupTimeoutSeconds;
private readonly bool _funAsrUsePersistentWorker;
private readonly double _funAsrMinSegmentSeconds;
private Task<FunAsrRuntimeBootstrapResult> _funAsrBootstrapTask;
private readonly List<byte> _asrSegmentBuffer = new List<byte>(16000 * 2 * 12);
private readonly SemaphoreSlim _funAsrRecognitionSemaphore = new SemaphoreSlim(1, 1);
private Process _funAsrWorkerProcess;
private StreamWriter _funAsrWorkerInput;
private StreamReader _funAsrWorkerOutput;
private string _funAsrWorkerLastErr = string.Empty;
private readonly object _funAsrWorkerErrLock = new object();
private DateTime _funAsrWorkerStdoutLogUtc = DateTime.MinValue;
private bool _funAsrScriptMissingLogged;
private bool _funAsrPythonMissingLogged;
private bool _funAsrRepairInProgress;
private int _funAsrAutoRepairAttempts;
private int _funAsrFailureCount;
private bool _classicFallbackEnabled;
private bool _funAsrRuntimeReady;
private bool _funAsrBootstrapMonitorStarted;
private CancellationTokenSource _funAsrRetryCts;
private int _recognizingStateEpoch;
private DateTime _lastRecognizingTouchUtc = DateTime.MinValue;
private string _lastRecognizedText;
private DateTime _lastRecognizedTextTime = DateTime.MinValue;
private DateTime _lastSpeechTime = DateTime.MinValue;
private System.Timers.Timer _silenceTimer;
private WaveInEvent _waveIn;
private WasapiCapture _wasapi;
private bool _enabled;
// 意图识别和草稿管理
private IntentRecognizer _intentRecognizer;
private TaskDraftManager _draftManager;
private VoiceReminderTimeParser _reminderTimeParser;
// VAD 参数 - 更保守的配置
private double _energyThresholdDb = -30.0; // 能量阈值,-30dBFS 表示要有一定音量
private int _minStartMs = 260; // 连续高能量达到 260ms 即可开始,减少首句漏检
private int _hangoverMs = 900; // 连续低能量达到 900ms 即停止,提升响应速度
private int _consecAboveMs = 0;
private int _consecBelowMs = 0;
private DateTime _lastAudioStateSpeech = DateTime.MinValue;
// 是否正在录音(用于写入文件)
private bool _isRecording = false;
// 统计
public int TotalSpeechDetections { get; private set; }
public int TotalPotentialTasks { get; private set; }
public DateTime? LastDetectionTime { get; private set; }
public EnhancedAudioCaptureService(TimeSpan? silenceTimeout = null, float confidenceThreshold = 0.5f)
{
_silenceTimeout = silenceTimeout ?? TimeSpan.FromSeconds(30);
_confidenceThreshold = confidenceThreshold;
_intentRecognizer = new IntentRecognizer();
_draftManager = new TaskDraftManager();
_reminderTimeParser = new VoiceReminderTimeParser();
_speechModelManager = new SpeechModelManager();
_modelBootstrapTask = _speechModelManager.EnsureReadyAsync();
_autoAddVoiceTasks = ReadBoolSetting("VoiceAutoAddToQuadrant", false);
_autoAddMinConfidence = ReadFloatSetting("VoiceAutoAddMinConfidence", 0.65f);
_useLlmForVoiceQuadrant = ReadBoolSetting("VoiceUseLlmQuadrant", false);
_requireDraftConfirmation = ReadBoolSetting("VoiceRequireConfirmation", true);
_conversationExtractEnabled = ReadBoolSetting("VoiceConversationExtractEnabled", true);
_conversationWindow = TimeSpan.FromSeconds(ReadIntSetting("VoiceConversationWindowSeconds", 45));
_conversationMinTurns = ReadIntSetting("VoiceConversationMinTurns", 3);
_speakerService = new SpeakerVerificationService();
_speakerVerifyEnabled = ReadBoolSetting("VoiceSpeakerVerifyEnabled", false);
_speakerEnrollMode = ReadBoolSetting("VoiceSpeakerEnrollMode", false);
_speakerThreshold = ReadDoubleSetting("VoiceSpeakerThreshold", 0.72);
_speakerMinSeconds = ReadDoubleSetting("VoiceSpeakerMinSeconds", 2.0);
_useStrictVoskGrammar = ReadBoolSetting("VoiceUseStrictVoskGrammar", false);
_systemSpeechUseHints = ReadBoolSetting("VoiceSystemSpeechUseHints", false);
_asrProvider = ReadStringSetting("VoiceAsrProvider", "hybrid");
_funAsrEnabled = _asrProvider.IndexOf("funasr", StringComparison.OrdinalIgnoreCase) >= 0;
_funAsrOnlyMode = string.Equals(_asrProvider, "funasr", StringComparison.OrdinalIgnoreCase);
_funAsrPythonExe = ReadStringSetting("FunAsrPythonExe", "python");
_funAsrScriptPath = ReadStringSetting("FunAsrScriptPath", @"scripts\funasr_asr.py");
_funAsrModel = ReadStringSetting("FunAsrModel", "iic/SenseVoiceSmall");
_funAsrDevice = ReadStringSetting("FunAsrDevice", "cpu");
_funAsrTimeoutSeconds = ReadIntSetting("FunAsrTimeoutSeconds", 45);
_funAsrWorkerStartupTimeoutSeconds = ReadIntSetting("FunAsrWorkerStartupTimeoutSeconds", 600);
_funAsrUsePersistentWorker = ReadBoolSetting("FunAsrUsePersistentWorker", true);
_funAsrMinSegmentSeconds = ReadDoubleSetting("FunAsrMinSegmentSeconds", 0.5);
_energyThresholdDb = ReadDoubleSetting("VoiceEnergyThresholdDb", -30.0);
_minStartMs = ReadIntSetting("VoiceVadMinStartMs", 260);
_hangoverMs = ReadIntSetting("VoiceVadHangoverMs", 900);
if (_funAsrEnabled)
{
VoiceRuntimeLog.Info($"EnhancedAudioCaptureService ctor: requesting FunASR bootstrap task. provider={_asrProvider}");
_funAsrBootstrapTask = FunAsrRuntimeManager.EnsureReadyAsync();
}
else
{
VoiceRuntimeLog.Info($"EnhancedAudioCaptureService ctor: FunASR disabled by provider={_asrProvider}");
}
}
/// <summary>
/// 启动持续监听
/// </summary>
public void Start()
{
lock (_lock)
{
if (_enabled) return;
_enabled = true;
VoiceListenerStatusCenter.Publish(VoiceListenerState.Unavailable, "语音监听不可用(初始化中)");
Console.WriteLine("[EnhancedAudioCaptureService] Starting...");
VoiceRuntimeLog.Info("EnhancedAudioCaptureService starting.");
bool voskReady = false;
if (!_funAsrOnlyMode)
{
// 初始化语音识别
try
{
TryWaitModelBootstrap();
voskReady = TryInitializeVoskRecognizer();
if (!voskReady)
{
InitializeSystemSpeechRecognizer();
}
if (!voskReady && _recognizer == null && !_funAsrEnabled)
{
throw new InvalidOperationException("Vosk 和 System.Speech 均未初始化成功。");
}
}
catch (Exception ex)
{
Console.WriteLine($"[EnhancedAudioCaptureService] Failed to start speech recognition: {ex.Message}");
VoiceRuntimeLog.Error("Failed to start speech recognition.", ex);
VoiceListenerStatusCenter.Publish(VoiceListenerState.Unavailable, "语音引擎初始化失败");
throw new InvalidOperationException("语音识别初始化失败,请检查系统语音识别组件和麦克风权限。", ex);
}
}
if (_funAsrEnabled)
{
StartFunAsrBootstrapMonitor();
TryWaitFunAsrBootstrap(TimeSpan.FromSeconds(2));
var resolvedScript = ResolveFunAsrScriptPath();
if (string.IsNullOrWhiteSpace(resolvedScript))
{
VoiceListenerStatusCenter.Publish(VoiceListenerState.Unavailable, "FunASR 脚本缺失,语音监听不可用");
throw new InvalidOperationException($"FunASR 脚本不存在:{_funAsrScriptPath}");
}
VoiceRuntimeLog.Info($"FunASR subprocess enabled. provider={_asrProvider}, python={_funAsrPythonExe}, script={resolvedScript}, model={_funAsrModel}, device={_funAsrDevice}, persistentWorker={_funAsrUsePersistentWorker}, timeoutSec={_funAsrTimeoutSeconds}");
}
// 启动静音检测定时器
_silenceTimer = new System.Timers.Timer(1000);
_silenceTimer.Elapsed += OnSilenceTick;
_silenceTimer.AutoReset = true;
_silenceTimer.Start();
// 启动音频采集
StartAudioCapture();
if (!voskReady && !_funAsrOnlyMode)
{
HookLateVoskInitialization();
}
Console.WriteLine("[EnhancedAudioCaptureService] Started successfully.");
VoiceRuntimeLog.Info("EnhancedAudioCaptureService started successfully.");
bool canListen = IsRecognitionPipelineAvailable();
if (canListen)
{
VoiceListenerStatusCenter.Publish(VoiceListenerState.Ready, "语音监听可用");
}
else
{
VoiceListenerStatusCenter.Publish(VoiceListenerState.Unavailable, "FunASR 尚未就绪,语音监听不可用");
}
}
}
/// <summary>
/// 停止监听
/// </summary>
public void Stop()
{
lock (_lock)
{
_enabled = false;
Console.WriteLine("[EnhancedAudioCaptureService] Stopping...");
try { _silenceTimer?.Stop(); } catch { }
_silenceTimer?.Dispose();
_silenceTimer = null;
if (_recognizer != null)
{
try { _recognizer.RecognizeAsyncCancel(); } catch { }
try { _recognizer.RecognizeAsyncStop(); } catch { }
_recognizer.SpeechRecognized -= OnSpeechRecognized;
_recognizer.SpeechHypothesized -= OnSpeechHypothesized;
_recognizer.AudioStateChanged -= OnAudioStateChanged;
_recognizer.Dispose();
_recognizer = null;
}
if (_voskRecognizer != null)
{
try { _voskRecognizer.Dispose(); } catch { }
_voskRecognizer = null;
}
if (_voskModel != null)
{
try { _voskModel.Dispose(); } catch { }
_voskModel = null;
}
_voskEnabled = false;
StopAudioCapture();
CancelFunAsrRetry();
StopFunAsrWorker();
Console.WriteLine("[EnhancedAudioCaptureService] Stopped.");
VoiceRuntimeLog.Info("EnhancedAudioCaptureService stopped.");
ResetRecognizingStateTimer();
VoiceListenerStatusCenter.Publish(VoiceListenerState.Unavailable, "语音监听已停止");
}
}
private void StartAudioCapture()
{
try
{
// 使用 16kHz 采样率 (语音足够用,降低资源消耗)
_waveIn = new WaveInEvent
{
WaveFormat = new WaveFormat(16000, 16, 1), // 16kHz, 16bit, Mono
BufferMilliseconds = 200
};
_waveIn.DataAvailable += OnWaveData;
_waveIn.RecordingStopped += OnRecordingStopped;
_waveIn.StartRecording();
Console.WriteLine("[EnhancedAudioCaptureService] Audio capture started (16kHz).");
}
catch (Exception ex)
{
Console.WriteLine($"[EnhancedAudioCaptureService] WaveIn start failed: {ex.Message}");
VoiceRuntimeLog.Error("WaveIn start failed.", ex);
TryFallbackToWasapi();
}
}
private void TryFallbackToWasapi()
{
try
{
if (_waveIn != null)
{
try { _waveIn.DataAvailable -= OnWaveData; } catch { }
try { _waveIn.RecordingStopped -= OnRecordingStopped; } catch { }
_waveIn.Dispose();
}
_waveIn = null;
var enumerator = new MMDeviceEnumerator();
var device = enumerator.GetDefaultAudioEndpoint(DataFlow.Capture, Role.Multimedia);
_wasapi = new WasapiCapture(device);
_wasapi.ShareMode = AudioClientShareMode.Shared;
// 尽量统一到 16k/16bit/mono,避免 Vosk 因格式不匹配而被跳过。
_wasapi.WaveFormat = new WaveFormat(16000, 16, 1);
_wasapi.DataAvailable += OnWaveData;
_wasapi.RecordingStopped += OnRecordingStopped;
_wasapi.StartRecording();
Console.WriteLine("[EnhancedAudioCaptureService] Fallback to WASAPI successful.");
VoiceRuntimeLog.Info("WASAPI fallback capture started.");
}
catch (Exception ex2)
{
Console.WriteLine($"[EnhancedAudioCaptureService] WASAPI fallback failed: {ex2.Message}");
VoiceRuntimeLog.Error("WASAPI fallback failed.", ex2);
}
}
private void StopAudioCapture()
{
try
{
_isRecording = false;
if (_waveIn != null)
{
try { _waveIn.StopRecording(); } catch { }
}
if (_wasapi != null)
{
try { _wasapi.StopRecording(); } catch { }
}
}
catch { }
}
private void OnSpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
{
if (!_enabled) return;
_lastSpeechTime = DateTime.UtcNow;
}
private void OnAudioStateChanged(object sender, AudioStateChangedEventArgs e)
{
if (e.AudioState == AudioState.Speech)
{
_lastAudioStateSpeech = DateTime.UtcNow;
}
}
private void OnSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!_enabled || e == null || e.Result == null) return;
var bestCandidate = SelectBestCandidate(e);
if (bestCandidate == null)
{
VoiceRuntimeLog.Info($"System.Speech ignored: text={e.Result.Text}, conf={e.Result.Confidence:F2}");
return;
}
HandleRecognizedText(bestCandidate.Text, bestCandidate.Confidence, "system-speech");
}
private string CleanRecognizedText(string text)
{
if (string.IsNullOrWhiteSpace(text)) return text;
// 清理 SenseVoice 常见标签,如 <|zh|><|NEUTRAL|><|Speech|>
text = Regex.Replace(text, @"<\|[^|>]+\|>", "");
// 移除多余的空白
text = Regex.Replace(text, @"\s+", " ");
text = text.Trim();
// 移除常见的识别错误
text = Regex.Replace(text, @"^[,,。.]\s*", "");
text = text.Trim(',', '。', '.', ',');
// 合并中文字符之间的空格(例如 "我 明天 的 会议" -> "我明天的会议")
text = Regex.Replace(text, @"(?<=[\u4e00-\u9fa5])\s+(?=[\u4e00-\u9fa5])", "");
// 常见口头/识别噪声前缀清理
text = Regex.Replace(text, @"^(编辑行|编辑|嗯|那个|就是|请|麻烦)\s*", "", RegexOptions.IgnoreCase);
// 若只剩问号/占位符,视为无效文本
if (Regex.IsMatch(text, @"^[\?\uFF1F\.\,\!\s]+$"))
{
return string.Empty;
}
return text;
}
private TaskDraft ProcessPotentialTask(string text, float confidence)
{
try
{
// 提取任务描述
string cleanedText = _intentRecognizer.ExtractTaskDescription(text);
if (string.IsNullOrWhiteSpace(cleanedText))
return null;
DateTime? reminderTime = null;
if (_reminderTimeParser != null && _reminderTimeParser.TryParse(text, DateTime.Now, out DateTime parsedTime))
{
reminderTime = parsedTime;
}
// 估计优先级
var (importance, urgency) = _intentRecognizer.EstimatePriority(cleanedText);
// 估计象限
string quadrant = _intentRecognizer.EstimateQuadrant(importance, urgency);
// 创建草稿
var draft = new TaskDraft
{
RawText = text,
CleanedText = cleanedText,
ReminderTime = reminderTime,
ReminderHintText = reminderTime.HasValue ? reminderTime.Value.ToString("yyyy-MM-dd HH:mm") : null,
Importance = importance,
Urgency = urgency,
EstimatedQuadrant = quadrant,
Source = "voice"
};
_draftManager.AddDraft(draft);
Console.WriteLine($"[EnhancedAudioCaptureService] Task draft created: \"{cleanedText}\" (Quadrant: {quadrant}, Conf: {confidence:P0}, Reminder: {reminderTime?.ToString("yyyy-MM-dd HH:mm") ?? "none"})");
VoiceRuntimeLog.Info($"Task draft created from voice. text={cleanedText}, quadrant={quadrant}, conf={confidence:F2}, reminder={reminderTime?.ToString("o") ?? "none"}");
return draft;
}
catch (Exception ex)
{
Console.WriteLine($"[EnhancedAudioCaptureService] Error processing potential task: {ex.Message}");
VoiceRuntimeLog.Error("ProcessPotentialTask failed.", ex);
return null;
}
}
private void OnSilenceTick(object sender, ElapsedEventArgs e)
{
if (!_enabled) return;
var now = DateTime.UtcNow;
// 超过静默阈值则停止录音
if (_isRecording && now - _lastSpeechTime > _silenceTimeout)
{
lock (_lock)
{
if (_isRecording && now - _lastSpeechTime > _silenceTimeout)
{
StopAudioCapture();
Console.WriteLine("[EnhancedAudioCaptureService] Silence timeout, stopped recording.");
EvaluateCompletedSegment(_waveIn?.WaveFormat ?? _wasapi?.WaveFormat);
}
}
}
}
private void OnWaveData(object sender, WaveInEventArgs e)
{
if (!_enabled) return;
var format = _waveIn?.WaveFormat ?? (_wasapi?.WaveFormat);
if (format == null || e.BytesRecorded <= 0) return;
// 在 funasr-only 且运行时未就绪时,不进入分段录音流程,避免“界面不可用但后台在录音”的矛盾状态。
if (!IsRecognitionPipelineAvailable())
{
lock (_lock)
{
_isRecording = false;
_consecAboveMs = 0;
_consecBelowMs = 0;
}
lock (_speechBuffer) { _speechBuffer.Clear(); }
lock (_asrSegmentBuffer) { _asrSegmentBuffer.Clear(); }
return;
}
if (!string.Equals(_asrProvider, "funasr", StringComparison.OrdinalIgnoreCase) || _classicFallbackEnabled)
{
TryProcessVoskAudio(e.Buffer, e.BytesRecorded, format);
}
CaptureSpeechBufferIfNeeded(e.Buffer, e.BytesRecorded);
// 计算帧时长(毫秒)
int bytesPerMs = format.AverageBytesPerSecond / 1000;
int frameMs = Math.Max(1, e.BytesRecorded / Math.Max(1, bytesPerMs));
// 计算 dBFS
double db = ComputeDbfs(e.Buffer, e.BytesRecorded, format);
bool above = db >= _energyThresholdDb;
lock (_lock)
{
if (above)
{
_consecAboveMs += frameMs;
_consecBelowMs = 0;
_lastSpeechTime = DateTime.UtcNow;
}
else
{
_consecBelowMs += frameMs;
_consecAboveMs = 0;
}
}
bool recentAudioSpeech = (DateTime.UtcNow - _lastAudioStateSpeech) < TimeSpan.FromSeconds(1.0);
bool vadOnlyStart = string.Equals(_asrProvider, "funasr", StringComparison.OrdinalIgnoreCase);
lock (_lock)
{
// 开始录音条件
if (!_isRecording)
{
if ((recentAudioSpeech || vadOnlyStart) && _consecAboveMs >= _minStartMs)
{
_isRecording = true;
TouchRecognizingState();
Console.WriteLine("[EnhancedAudioCaptureService] Started recording (VAD triggered).");
}
}
else
{
if (above || _consecBelowMs < _hangoverMs)
{
TouchRecognizingState();
}
// 停止录音条件
if (_consecBelowMs >= _hangoverMs)
{
_isRecording = false;
Console.WriteLine("[EnhancedAudioCaptureService] Stopped recording (silence detected).");
EvaluateCompletedSegment(format);
}
}
// 注意:这里不再写入文件,只做 VAD 检测
}
}
private void OnRecordingStopped(object sender, StoppedEventArgs e)
{
lock (_lock)
{
_isRecording = false;
try
{
if (_waveIn != null)
{
_waveIn.DataAvailable -= OnWaveData;
_waveIn.RecordingStopped -= OnRecordingStopped;
}
if (_wasapi != null)
{
_wasapi.DataAvailable -= OnWaveData;
_wasapi.RecordingStopped -= OnRecordingStopped;
}
}
catch { }
_waveIn?.Dispose();
_waveIn = null;
_wasapi?.Dispose();
_wasapi = null;
}
}
private static double ComputeDbfs(byte[] buffer, int bytes, WaveFormat format)
{
try
{
if (format.BitsPerSample == 16)
{
int samples = bytes / 2;
if (samples == 0) return double.NegativeInfinity;
double sumSq = 0;
for (int i = 0; i < bytes; i += 2)
{
short s = BitConverter.ToInt16(buffer, i);
double norm = s / 32768.0;
sumSq += norm * norm;
}
double rms = Math.Sqrt(sumSq / samples);
double dbfs = 20.0 * Math.Log10(rms + 1e-12);
return (!double.IsNaN(dbfs) && !double.IsInfinity(dbfs)) ? dbfs : double.NegativeInfinity;
}
}
catch { }
return double.NegativeInfinity;
}
private void TryUpdateRecognizerSetting(string name, TimeSpan value)
{
try { _recognizer?.UpdateRecognizerSetting(name, (int)value.TotalMilliseconds); }
catch { }
}
private void TryWaitModelBootstrap()
{
try
{
if (_modelBootstrapTask == null) return;
if (_modelBootstrapTask.Wait(TimeSpan.FromSeconds(2)))
{
var result = _modelBootstrapTask.Result;
Console.WriteLine($"[EnhancedAudioCaptureService] Model bootstrap ready={result.IsReady}, source={result.Source}, msg={result.Message}");
VoiceRuntimeLog.Info($"Model bootstrap result: ready={result.IsReady}, source={result.Source}, msg={result.Message}");
}
else
{
Console.WriteLine("[EnhancedAudioCaptureService] Model bootstrap running in background.");
VoiceRuntimeLog.Info("Model bootstrap is still running in background.");
}
}
catch (Exception ex)
{
Console.WriteLine($"[EnhancedAudioCaptureService] Model bootstrap check failed: {ex.Message}");
VoiceRuntimeLog.Error("Model bootstrap check failed.", ex);
}
}
private void TryLoadHintsGrammar()
{
try
{
string hintsPath = _speechModelManager.GetHintsFilePath();
if (!File.Exists(hintsPath))
return;
var phrases = File.ReadAllLines(hintsPath, Encoding.UTF8)
.Select(l => l?.Trim())
.Where(l => !string.IsNullOrWhiteSpace(l))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(300)
.ToList();
if (!phrases.Any())
return;
_hintPhrases.Clear();
foreach (var phrase in phrases)
{
_hintPhrases.Add(phrase);
}
var choices = new Choices(phrases.ToArray());
var grammar = new Grammar(new GrammarBuilder(choices))
{
Name = "task-hints"
};
_recognizer.LoadGrammar(grammar);
Console.WriteLine($"[EnhancedAudioCaptureService] Loaded hints grammar, phrases={phrases.Count}");
VoiceRuntimeLog.Info($"Hints grammar loaded, count={phrases.Count}, file={hintsPath}");
}
catch (Exception ex)
{
Console.WriteLine($"[EnhancedAudioCaptureService] Failed to load hints grammar: {ex.Message}");
VoiceRuntimeLog.Error("Failed to load hints grammar.", ex);
}
}
private void TryLoadVoskGrammar()
{
try
{
string hintsPath = _speechModelManager.GetHintsFilePath();
if (!File.Exists(hintsPath))
return;
var phrases = File.ReadAllLines(hintsPath, Encoding.UTF8)
.Select(l => l?.Trim())
.Where(l => !string.IsNullOrWhiteSpace(l))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(300)
.ToList();
if (!phrases.Any())
return;
_hintPhrases.Clear();
foreach (var phrase in phrases)
{
_hintPhrases.Add(phrase);
}
if (!_useStrictVoskGrammar)
{
VoiceRuntimeLog.Info("Vosk grammar hints loaded for ranking only (strict grammar disabled).");
return;
}
if (!phrases.Contains("[unk]", StringComparer.OrdinalIgnoreCase))
{
phrases.Add("[unk]");
}
string grammarJson = Newtonsoft.Json.JsonConvert.SerializeObject(phrases);
if (_voskRecognizer != null)
{
var method = _voskRecognizer.GetType().GetMethod("SetGrammar", new[] { typeof(string) });
if (method != null)
{
method.Invoke(_voskRecognizer, new object[] { grammarJson });
VoiceRuntimeLog.Info($"Vosk grammar loaded, phrases={phrases.Count}");
}
else
{
VoiceRuntimeLog.Info("Vosk grammar not supported by current Vosk library. Skip SetGrammar.");
}
}
}
catch (Exception ex)
{
VoiceRuntimeLog.Error("Failed to load Vosk grammar.", ex);
}
}
private bool TryInitializeVoskRecognizer()
{
try
{
if (_modelBootstrapTask == null || !_modelBootstrapTask.IsCompleted)
{
VoiceRuntimeLog.Info("Vosk init skipped: model bootstrap not completed yet.");
return false;
}
var result = _modelBootstrapTask.Result;
if (!result.IsReady || string.IsNullOrWhiteSpace(result.ModelDirectory) || !Directory.Exists(result.ModelDirectory))
{
VoiceRuntimeLog.Info($"Vosk init skipped: model not ready. msg={result.Message}");
return false;
}
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string nativeDll = Path.Combine(baseDir, "libvosk.dll");
VoiceRuntimeLog.Info($"Vosk native dll exists: {File.Exists(nativeDll)} path={nativeDll}");
Vosk.Vosk.SetLogLevel(-1);
_voskModel = new Model(result.ModelDirectory);
_voskRecognizer = new VoskRecognizer(_voskModel, 16000.0f);
_voskRecognizer.SetMaxAlternatives(3);
_voskRecognizer.SetWords(true);
TryLoadVoskGrammar();
_voskEnabled = true;
VoiceRuntimeLog.Info($"Vosk recognizer initialized. modelDir={result.ModelDirectory}");
return true;
}
catch (Exception ex)
{
_voskEnabled = false;
VoiceRuntimeLog.Error($"Vosk recognizer initialization failed. ProcessBitness={(Environment.Is64BitProcess ? "x64" : "x86")}", ex);
return false;
}
}
private void HookLateVoskInitialization()
{
if (_modelBootstrapTask == null || _modelBootstrapTask.IsCompleted)
return;
_modelBootstrapTask.ContinueWith(t =>
{
if (t.IsFaulted || !_enabled)
return;
lock (_lock)
{
if (!_enabled || _voskEnabled)
return;
bool ready = TryInitializeVoskRecognizer();
if (ready)
{
VoiceRuntimeLog.Info("Vosk recognizer initialized after delayed model bootstrap.");
}
}
}, TaskScheduler.Default);
}
private void InitializeSystemSpeechRecognizer()
{
_recognizer = CreateRecognizer();
_recognizer.SetInputToDefaultAudioDevice();
_recognizer.LoadGrammar(new DictationGrammar());
if (_systemSpeechUseHints)
{
TryLoadHintsGrammar();
}
TryUpdateRecognizerSetting("BabbleTimeout", TimeSpan.FromSeconds(3));
TryUpdateRecognizerSetting("InitialSilenceTimeout", TimeSpan.FromSeconds(6));
_recognizer.SpeechRecognized += OnSpeechRecognized;
_recognizer.SpeechHypothesized += OnSpeechHypothesized;
_recognizer.AudioStateChanged += OnAudioStateChanged;
_recognizer.RecognizeAsync(RecognizeMode.Multiple);
Console.WriteLine("[EnhancedAudioCaptureService] System.Speech recognition started.");
VoiceRuntimeLog.Info("System.Speech recognizer started.");
}
private void TryProcessVoskAudio(byte[] buffer, int bytesRecorded, WaveFormat format)
{
if (!_voskEnabled || _voskRecognizer == null)
return;
if (format.SampleRate != 16000 || format.BitsPerSample != 16 || format.Channels != 1)
{
if (!_voskFormatWarningLogged)
{
_voskFormatWarningLogged = true;
VoiceRuntimeLog.Info($"Vosk audio format not supported directly: {format.SampleRate}Hz/{format.BitsPerSample}bit/{format.Channels}ch");
}
return;
}
bool isFinal = _voskRecognizer.AcceptWaveform(buffer, bytesRecorded);
if (!isFinal)
return;
string finalJson = _voskRecognizer.Result();
var parsed = ParseVoskFinalResult(finalJson);
if (string.IsNullOrWhiteSpace(parsed.text))
return;
HandleRecognizedText(parsed.text, parsed.confidence, "vosk");
}
private (string text, float confidence) ParseVoskFinalResult(string json)
{
try
{
if (string.IsNullOrWhiteSpace(json))
return (string.Empty, 0f);
var root = JObject.Parse(json);
var words = root["result"] as JArray;
float wordAvgConf = 0.6f;
if (words != null && words.Count > 0)
{
var confs = words
.OfType<JObject>()
.Select(w => (float?)w["conf"])
.Where(c => c.HasValue)
.Select(c => c.Value)
.ToList();
if (confs.Count > 0)
{
wordAvgConf = confs.Average();
}
}
var alternatives = root["alternatives"] as JArray;
if (alternatives != null && alternatives.Count > 0)
{
var bestAlt = alternatives
.OfType<JObject>()
.Select(x => new
{
Text = (string)x["text"],
Confidence = (float?)x["confidence"] ?? wordAvgConf
})
.Select(x => new
{
x.Text,
x.Confidence,
Score = ScoreAlt(x.Text, x.Confidence)
})
.OrderByDescending(x => x.Score)
.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x.Text));
if (bestAlt != null)
return (bestAlt.Text, ClampConfidence(bestAlt.Confidence));
}
string text = (string)root["text"] ?? string.Empty;
if (words == null || words.Count == 0)
return (text, wordAvgConf);
return (text, ClampConfidence(wordAvgConf));
}
catch (Exception ex)
{
VoiceRuntimeLog.Error("Failed to parse Vosk result json.", ex);
return (string.Empty, 0f);
}
}
private double ScoreAlt(string text, float confidence)
{
if (string.IsNullOrWhiteSpace(text))
return 0;
string normalized = CleanRecognizedText(text);
if (string.IsNullOrWhiteSpace(normalized))
return 0;
double score = ClampConfidence(confidence);
score += (_intentRecognizer?.ScoreTaskLikelihood(normalized) ?? 0) * 0.25;
score += ScoreHintMatch(normalized);
if (Regex.IsMatch(normalized, @"^(嗯+|啊+|额+|哦+|那个|就是)$", RegexOptions.IgnoreCase))
{
score -= 0.25;
}
if (normalized.Length <= 2)
{
score -= 0.15;
}
return score;
}
private double ScoreHintMatch(string text)
{
if (string.IsNullOrWhiteSpace(text) || _hintPhrases.Count == 0)
return 0;
string normalized = text.Trim();
if (_hintPhrases.Contains(normalized))
return 0.20;
bool containsHint = _hintPhrases.Any(p => p.Length >= 2 && normalized.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0);
if (containsHint)
return 0.10;
return 0;
}
private static float ClampConfidence(float value)
{
if (float.IsNaN(value) || float.IsInfinity(value))
return 0f;
if (value > 1.0f)
{
// 兜底:异常大值统一压到 1.0
return 1.0f;
}
if (value < 0f)
return 0f;
return value;
}
private void HandleRecognizedText(string rawText, float confidence, string source)