首页 > 解决方案 > 使用语音识别时 C# 不必要的输入

问题描述

class Program
{
    static void Main(string[] args)
    {
        Brain b = new Brain();
        b.start();
    }
}
public class Map
{
    public string key;
    public string value;
    public Map(string key, string value)
    {
        this.key = key;
        this.value = value;
    }
}
public class Ears
{
    private SpeechRecognitionEngine ears;
    public Ears(List<Map> knowledge, EventHandler<SpeechRecognizedEventArgs> onRecognise, EventHandler<SpeechRecognitionRejectedEventArgs> onReject)
    {

        this.ears = new SpeechRecognitionEngine();

        Choices commands = new Choices();
        foreach (var item in knowledge)
        {
            commands.Add(item.key);
        }
        GrammarBuilder gBuilder = new GrammarBuilder();
        gBuilder.Append(commands);
        Grammar grammar = new Grammar(gBuilder);

        ears.LoadGrammar(grammar);
        ears.SetInputToDefaultAudioDevice();

        ears.RecognizeAsync(RecognizeMode.Multiple);
        ears.SpeechRecognized += onRecognise;
        ears.SpeechRecognitionRejected += onReject;

    }
    public void stop()
    {
        ears.RecognizeAsyncCancel();
    }
    public void start()
    {
        ears.RecognizeAsync(RecognizeMode.Multiple);
    }
}
public class Brain
{
    protected List<Map> commands;
    protected List<Map> answers;

    private readonly Ears ears;
    public Brain()
    {
        commands = new List<Map>();
        commands.Add(new Map("list",""));
        commands.Add(new Map("somethingElse","someValue"));
        ears = new Ears(commands, onRecognized, onRejected);
    }
    private void onRecognized(object sender, SpeechRecognizedEventArgs e)
    {
        Console.WriteLine(e.Result.Text);
        terminateCommands(new Map(e.Result.Text.Trim().ToLower(), null));
    }
    public void start() {
        while (true) {
            string answer = Console.ReadLine();
            if (answer!="")
            {
                terminateCommands(new Map(answer, null));
            }
        }
    }
    private void onRejected(object sender, SpeechRecognitionRejectedEventArgs e)
    {
    }
    private void terminateCommands(Map cmd) {
        Console.WriteLine("need user input");
        var answer = Console.ReadLine();
        Console.WriteLine("need user input again");
        var answer2 = Console.ReadLine();

    }
}

如果我使用键盘,'list' 方法工作得很好(由 terminateCommands 调用)。所以 terminateCommands 是从 'start' 方法调用的。但是,如果我使用 VoiceRecognition(基本的 Mycrosoft.Speech),并且从 eventHandler 调用 terminateCommands,则每次当 list 方法需要用户输入时,我都必须按 Enter,写 sg,然后再次按 Enter。似乎在“列表”方法中的每个 Console.ReadLine() 之前还有另一个 Console.ReadLine() 。ear.stop() 只是停止语音识别。Map 是一个类,包含 2 个字符串(值,键)。我有点困惑。任何想法?

标签: c#readlinespeech

解决方案


推荐阅读