如何在C# WinForm中获取Azure认知服务语音识别的置信度
获取Azure认知服务语音识别的置信度分数
要在你的Windows Forms语音转文本应用中获取识别结果的置信度分数,需要先显式启用Azure Speech SDK的置信度返回功能,然后从识别结果中提取对应信息。具体步骤如下:
1. 启用置信度返回
在初始化SpeechConfig时,添加配置启用置信度分数,同时如果需要词级别的置信度,还可以请求词级时间戳:
修改你的initRecognizer方法:
private void initRecognizer() { SpeechConfig config = SpeechConfig.FromSubscription("key", "region"); if (Properties.Settings.Default.Punctuation) { config.SetServiceProperty("punctuation", "explicit", ServicePropertyChannel.UriQueryParameter); } // 启用整体置信度分数返回 config.SetProperty(PropertyId.SpeechServiceResponse_ConfidenceScoreEnabled, "true"); // 启用词级置信度和时间戳(可选,按需添加) config.RequestWordLevelTimestamps(); //AudioConfig audioConfig = AudioConfig.FromMicrophoneInput(); recognizer = new SpeechRecognizer(config/*, audioConfig*/); recognizer.Recognized += SpeechRecognizer_Recognized; }
2. 从识别结果中提取置信度
在SpeechRecognizer_Recognized事件处理方法中,你可以获取整体置信度(枚举/数值)和词级置信度(可选):
修改后的事件处理代码:
using System.Text.Json; // 需要添加此命名空间,或使用Newtonsoft.Json private void SpeechRecognizer_Recognized(object sender, SpeechRecognitionEventArgs e) { if (e.Result.Reason == ResultReason.RecognizedSpeech) { // 1. 获取整体置信度(枚举类型:High/Medium/Low/None) SpeechConfidence overallConfidence = e.Result.Confidence; string confidenceInfo = $"整体置信度级别: {overallConfidence}"; // 2. 获取整体置信度的数值分数(0-1之间,需解析原始JSON响应) string jsonResponse = e.Result.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult); using (JsonDocument doc = JsonDocument.Parse(jsonResponse)) { var root = doc.RootElement; if (root.GetProperty("RecognitionStatus").GetString() == "Success") { double numericConfidence = root.GetProperty("NBest")[0].GetProperty("Confidence").GetDouble(); confidenceInfo += $",数值分数: {numericConfidence:F2}"; } } // 3. 获取词级置信度(如果之前启用了RequestWordLevelTimestamps) if (e.Result.WordLevelResults != null && e.Result.WordLevelResults.Any()) { StringBuilder wordConfidenceBuilder = new StringBuilder("\n词级置信度详情:"); foreach (var wordResult in e.Result.WordLevelResults) { wordConfidenceBuilder.AppendLine($"\n- 词汇: {wordResult.Word},置信度分数: {wordResult.Confidence:F2}"); } confidenceInfo += wordConfidenceBuilder.ToString(); } // 这里可以将置信度信息展示出来,比如写入文本框或日志 // 示例:假设你有一个名为txtConfidence的TextBox控件 // txtConfidence.Text = confidenceInfo; // 原有输入模拟逻辑 if (e.Result.Text.ToLower().Equals("new line") || e.Result.Text.ToLower().Equals("newline")) { SendKeys.SendWait(Environment.NewLine); } else { SendKeys.SendWait(e.Result.Text); } } }
注意事项
- 如果使用.NET Framework开发,需要通过NuGet安装
System.Text.Json或Newtonsoft.Json包来解析JSON响应。 - 数值置信度分数范围为0到1,越接近1表示识别结果越准确。
- 词级置信度需要提前通过
config.RequestWordLevelTimestamps()启用,否则e.Result.WordLevelResults会为空。
内容的提问来源于stack exchange,提问作者Babar Ali
相关产品推荐
相关产品推荐

