我正在尝试创建一个简单的语音控制应用程序,它像cortana一样被激活。当我说一些像“香蕉”这样的特定内容时,我想让应用程序听取命令。这是我的代码:
public async Task SetupRecognizer()
{
var WebGrammar = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "webSearch");
Recognizer.Timeouts.InitialSilenceTimeout = TimeSpan.FromSeconds(6.0);
Recognizer.Timeouts.BabbleTimeout = TimeSpan.FromSeconds(4.0);
Recognizer.Timeouts.EndSilenceTimeout = TimeSpan.FromSeconds(1.2);
Recognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
await Recognizer.CompileConstraintsAsync();
}
public async Task Listen()
{
MessageDialog md = new MessageDialog("Now Listening", "Listening");
await md.ShowAsync();
await SetupRecognizer();
SpeechRecognitionResult Result = await Recognizer.RecognizeAsync();
await ExecuteCommand(Result.Text);
if (ShouldShowSpeechRecognitionResult)
{
MessageDialog dialog = new MessageDialog(Result.Text, "Result");
await dialog.ShowAsync();
}
}
public async Task ListenFor()
{
ThisPage.ListenButton.IsEnabled = false;
await SetupRecognizer();
await Recognizer.ContinuousRecognitionSession.StartAsync(SpeechContinuousRecognitionMode.Default);
}
private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
{
if (args.Result.Text.Contains("banana"))
{
await Recognizer.ContinuousRecognitionSession.CancelAsync();
await Listen();
}
}
(ListenFor()
任务由按钮点击事件调用。)
当我运行应用程序并说“banana”时,它会调用Recognizer.ContinuousRecognitionSession.CancelAsync()
函数,但当它转到'Listen()时,Visual Studio会抛出异常:
'The application called an interface that was marshalled for a different thread.
(Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'