取消Windows Phone 8语音识别会话



我有一个Windows Phone 8应用程序,使用SpeechRecognizer类(不是 SpeechRecognizerUI)做语音识别。如何取消正在进行的会话?我没有在语音识别类中看到取消或停止方法。

UPDATE:我想根据这个MSDN线程给mparkuk的答案提供上下文:

SpeechRecognizer.Settings。InitialSilenceTimeout不能正常工作

取消语音识别操作的方法是维护对识别器的IAsyncOperation调用返回的IAsyncOperation的引用,而不是通过直接等待 RecoAsync()调用来"丢弃它"以获得识别结果。我包括下面的代码,以防线程丢失随着时间的推移。取消语音识别会话的要点是调用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高级升级工程师| Microsoft开发人员支持| Windows Phone 8

关于取消机制,这里是一些开发人员建议的代码。

由RecognizeAsync返回的IAsyncOperation有一个Cancel函数

你必须:

1)将初始沉默超时设置为较大的值(例如:所需语音输入超时的两倍,在我的情况下为10秒)reco.Settings.InitialSilenceTimeout = TimeSpan。FromMilliseconds(2 * speech puttimeoutmsec);

2)存储这个。currentRecoOperation = this.recognizer.RecognizeAsync();

3)如果需要,在10秒后启动一个工作线程以取消操作。我不想冒任何风险,所以我还添加了代码,以便在检测到挂起时重新初始化所有内容。这是通过查看音频捕获状态是否在开始识别的几秒钟内变为捕获来完成的。

你看过这个帖子吗?

SpeechRecognizer.Settings。InitialSilenceTimeout不能正常工作

相关内容

  • 没有找到相关文章

最新更新