【问题标题】:Cancel a Windows Phone 8 speech recognition session?取消 Windows Phone 8 语音识别会话?
【发布时间】:2014-03-14 01:46:29
【问题描述】:

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

更新:我想根据这个 MSDN 线程为 mparkuk 的答案提供上下文:

SpeechRecognizer.Settings.InitialSilenceTimeout not working right

取消语音识别操作的方法是保持对识别器 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 线程 ------ -------------

Credit: Mark Chamberlain Sr. Escalation Engineer |微软开发者支持 | Windows 电话 8

关于取消机制,这里有一些开发者建议的代码。

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

你必须:

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

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

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

【问题讨论】:

    标签: c# windows-phone-8 speech-recognition


    【解决方案1】:

    【讨论】:

    • 不,我没有感谢。我没想到要从识别器的 RecoAsync() 方法中获取 IAsyncOperation 接口引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多