我有一个Windows Phone 8应用程序,它使用 SpeechRecognizer 类(不是 SpeechRecognizerUI)来进行语音识别。如何取消正在进行的会话?我没有在SpeechRecognizer类中看到取消或停止方法。
更新:我想基于此MSDN主题为mparkuk的回答提供上下文:
SpeechRecognizer.Settings.InitialSilenceTimeout not working right
取消语音识别操作的方法是通过直接等待 RecoAsync来维护对识别器的 IAsyncOperation 调用返回的IAsyncOperation的引用,而不是“丢弃它” ()调用以获得识别结果。我将包含以下代码,以防线程随着时间的推移而丢失。取消语音识别会话的要点是调用 IAsyncOperation.Cancel()方法。
private const int SpeechInputTimeoutMSEC = 10000;
private SpeechRecognizer CreateRecognizerAndLoadGrammarAsync(string fileName, Uri grammarUri, out Task grammarLoadTask)
{
// Create the recognizer and start loading grammars
SpeechRecognizer reco = new SpeechRecognizer();
// @@BUGBUG: Set the silence detection to twice the configured time - we cancel it from the thread
reco.Settings.InitialSilenceTimeout = TimeSpan.FromMilliseconds(2 * SpeechInputTimeoutMSEC);
reco.AudioCaptureStateChanged += recognizer_AudioCaptureStateChanged;
reco.Grammars.AddGrammarFromUri(fileName, grammarUri);
// Start pre-loading grammars to minimize reco delays:
reco.PreloadGrammarsAsync();
return reco;
}
/// <summary>
/// Recognize async
/// </summary>
public async void RecognizeAsync()
{
try
{
// Start recognition asynchronously
this.currentRecoOperation = this.recognizer.RecognizeAsync();
// @@BUGBUG: Add protection code and handle speech timeout programmatically
this.SpeechBugWorkaround_RunHangProtectionCode(this.currentRecoOperation);
// Wait for the reco to complete (or get cancelled)
SpeechRecognitionResult result = await this.currentRecoOperation;
this.currentRecoOperation = null;
// Get the results
results = GetResults(result);
this.CompleteRecognition(results, speechError);
}
catch (Exception ex)
{
// error
this.CompleteRecognition(null, ex);
}
// Restore the recognizer for next operation if necessary
this.ReinitializeRecogizerIfNecessary();
}
private void SpeechBugWorkaround_RunHangProtectionCode(IAsyncOperation<SpeechRecognitionResult> speechRecoOp)
{
ThreadPool.QueueUserWorkItem(delegate(object s)
{
try
{
bool cancelled = false;
if (false == this.capturingEvent.WaitOne(3000) && speechRecoOp.Status == AsyncStatus.Started)
{
cancelled = true;
speechRecoOp.Cancel();
}
// If after 10 seconds we are still running - cancel the operation.
if (!cancelled)
{
Thread.Sleep(SpeechInputTimeoutMSEC);
if (speechRecoOp.Status == AsyncStatus.Started)
{
speechRecoOp.Cancel();
}
}
}
catch (Exception) { /* TODO: Add exception handling code */}
}, null);
}
private void ReinitializeRecogizerIfNecessary()
{
lock (this.sync)
{
// If the audio capture event was not raised, the recognizer hang -> re-initialize it.
if (false == this.capturingEvent.WaitOne(0))
{
this.recognizer = null;
this.CreateRecognizerAndLoadGrammarAsync(...);
}
}
}
/// <summary>
/// Handles audio capture events so we can tell the UI thread we are listening...
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void recognizer_AudioCaptureStateChanged(SpeechRecognizer sender, SpeechRecognizerAudioCaptureStateChangedEventArgs args)
{
if (args.State == SpeechRecognizerAudioCaptureState.Capturing)
{
this.capturingEvent.Set();
}
}
-------------------------------------来自MSDN线程------ -------------
图片来源:Mark Chamberlain Sr. Escalation Engineer | Microsoft开发人员支持| Windows Phone 8
关于取消机制,以下是开发人员提供的一些建议代码。
RecognizeAsync返回的IAsyncOperation具有Cancel功能。
你必须:
1)将初始静音超时设置为较大的值(例如:所需语音输入超时的两倍,在我的情况下为10秒)reco.Settings.InitialSilenceTimeout = TimeSpan.FromMilliseconds(2 * SpeechInputTimeoutMSEC);
2)存储this.currentRecoOperation = this.recognizer.RecognizeAsync();
3)如果需要,在10秒后启动工作线程以取消操作。我不想冒任何风险所以如果检测到挂起,我还添加了代码来重新初始化所有内容。这是通过查看音频捕获状态是否在开始识别的几秒钟内更改为捕获来完成的。