在Microsoft.Speech.Recognition中加载新语法

时间:2012-02-13 23:30:58

标签: c# multithreading c#-4.0 asynchronous speech-recognition

我正在构建一个使用新的microsoft.speech API的程序。当我第一次启动程序时,我用语法加载我的SpeechRecognizer,一切都很好。但是,我也使用Microsoft Async CTP做一些工作来检索要添加到语法中的单词,当它返回时我想加载一个新的语法。 Bellow是异步CTP部分......

class UR
{
    private CancellationTokenSource _cancelationToken;

    public UR()
    {
        _cancelationToken = new CancellationTokenSource();
    }

    public async void StartRecognition()
    {
        String someword = await Recognize(_cancelationToken.Token);
        //Load the new grammar
        SpeechRecognizer sr = SpeechRecognizer.Instance;
        sr.LoadNewGrammar(someword);
    }
}

这是LoadNewGrammar方法,为了加载新语法,您将看到我正在尝试使用“RecognizeAsyncCancel”来停止识别器,然后加载语法和用户“RecognizeAsync”以重新启动识别器。

    public void LoadNewGrammar(String someword)
    {
        Commands = new Dictionary<string, WhatSaid>()
        {
            {"DoThis",         new WhatSaid()      {verb=Verbs.DoThis}},
            {"DoThat",         new WhatSaid()      {verb=Verbs.DoThat}},
            {someword,         new WhatSaid()      {verb=Verbs.Someword}}
        };

        if (sre == null)
        {
            RecognizerInfo ri = GetKinectRecognizer();
            sre = new SpeechRecognitionEngine(ri);
        }
        //Stop the speech recognizer temporarily in order to load the new grammar
        sre.RecognizeAsyncCancel();

        // Build a grammar of commands
        var basicCmds = new Choices();
        foreach (var phrase in Commands)
        {
            basicCmds.Add(phrase.Key);
        }

        // Combine all choices 
        var allChoices = new Choices();
        allChoices.Add(basicCmds);

        //Create a grammar builder to be used in the grammar object
        var gb = new GrammarBuilder();
        gb.Culture = sre.RecognizerInfo.Culture; 
        gb.Append(allChoices);

        var g = new Grammar(gb);
        sre.LoadGrammar(g);
        sre.RecognizeAsync(RecognizeMode.Multiple);
    }

问题似乎是当我调用sre.RecognizeAsyncCancel时,我的程序完全冻结了。我也尝试了使用相同结果的RecognizeAsyncStop。我有一种感觉,因为我在这里有一个线程问题,但不知道从哪里开始解决这个问题。