为了使用 Windows 10 中发布的新 SpeechRecognition WinRT API,您需要在桌面 C# 应用程序中添加对 WinRT API 的支持。这不需要将应用程序转换为 Windows 应用商店应用程序,但是,至少对于某些部分而言。据我所知,新引擎尚未向后移植以向 System.Speech.SpeechRecognitionEngine 添加支持,该引擎仍使用旧版识别器(我将在此处与语音团队核实,如果我发现更多信息,请在本文中跟进在这一点上。)
根据here 和here 的指导,我能够创建一个经典的c# WPF 应用程序,并实现以下代码:
private SpeechRecognizer reco;
public MainWindow()
{
InitializeComponent();
reco = new SpeechRecognizer();
List<string> constraints = new List<string>();
constraints.Add("Yes");
constraints.Add("No");
reco.Constraints.Add(new SpeechRecognitionListConstraint(constraints));
IAsyncOperation<SpeechRecognitionCompilationResult> op = reco.CompileConstraintsAsync();
op.Completed += HandleCompilationCompleted;
}
public void HandleCompilationCompleted(IAsyncOperation<SpeechRecognitionCompilationResult> opInfo, AsyncStatus status)
{
if(status == AsyncStatus.Completed)
{
System.Diagnostics.Debug.WriteLine("CompilationCompleted");
var result = opInfo.GetResults();
System.Diagnostics.Debug.WriteLine(result.Status.ToString());
}
}
为了编译,我添加了
<PropertyGroup>
<TargetPlatformVersion>10.0</TargetPlatformVersion>
</PropertyGroup>
到 .csproj,并从 Project -> Add References -> Universal Windows -> Core 部分添加了 Windows.Media 和 Windows.Foundation,我还手动添加了对
的引用
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll
和
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.InteropServices.WindowsRuntime.dll
通过添加引用的浏览部分。
如果您的系统尚未默认使用 it-IT,您需要检查 SpeechRecognizer.SupportedGrammarLanguages 以检索 it-IT 语言对象以将其传递给识别器构造函数。 (如果您安装了意大利版本的 Windows 10,默认情况下应该会发生这种情况)
现在,我上面的代码 sn-p 只编译了一个超级简单的语法,它并没有开始识别。为此,您需要查阅 Windows.Media.SpeechRecognition API 的其余部分,但大体相同。