C#语音命令:等待输入

时间:2016-03-17 16:11:47

标签: c# winforms

我有一个识别语音命令的Windows窗体应用程序,然后相应地执行操作。但是,我无法弄清楚如何一个接一个地说出一个命令。

代码:

if (e.Result.Text == "initiate power saving mode")
{
    Taskbar taskbar = new Taskbar();
    taskbar.Show();
    SoundPlayer deacr = new SoundPlayer(Properties.Resources.deacr);
    deacr.PlaySync();
    if (e.Result.Text== "confirm")
    {
        SoundPlayer deacd = new SoundPlayer(Properties.Resources.deacd);
        deacd.PlaySync();
        Application.SetSuspendState(PowerState.Suspend, true, true);
    }
    else if (e.Result.Text == "cancel")
    {
        SoundPlayer cancelled = new SoundPlayer(Properties.Resources.cancelled);
        cancelled.PlaySync();                    
    }
}

我错过了什么,或者只是做错了什么?

1 个答案:

答案 0 :(得分:0)

你需要使用System.Speech。这就是我在我的系统上的表现。您可以执行以下操作:

using System.Speech.Synthesis;
using System.Speech.Recognition;

namespace Alexis
{
    public partial class frmMain : Form
    {
        SpeechRecognitionEngine _recognizer = new SpeechRecognitionEngine();
        SpeechSynthesizer Alexis = new SpeechSynthesizer();
        SpeechRecognitionEngine startlistening = new SpeechRecognitionEngine();
    }
// ...
}

然后以主要形式

private void frmMain_Load(object sender, EventArgs e)
    {

        _recognizer.SetInputToDefaultAudioDevice();
        _recognizer.LoadGrammarAsync(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(@"Default Commands.txt")))));

        _recognizer.SpeechDetected += new EventHandler<SpeechDetectedEventArgs>(_recognizer_SpeechDetected);
        _recognizer.RecognizeAsync(RecognizeMode.Multiple);

        startlistening.SetInputToDefaultAudioDevice();
        startlistening.LoadGrammarAsync(new Grammar(new GrammarBuilder(new Choices("alexis"))));
        startlistening.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(startlistening_SpeechRecognized);
    }

然后进行编码。现在,为了调用创建txt文档所需的命令。并在命令中一次输入一行(不要留下任何空行)。

        _recognizer.LoadGrammarAsync(new Grammar(new GrammarBuilder(new Choices(File.ReadAllLines(@"Default Commands.txt")))));

将触发命令,这样您就可以调用命令。我也不会使用if (e.Result.Text == "initiate power saving mode")我会这样使用if (speech == "initiate power saving mode") 所以,如果你想继续,你可以这样做

if (speech == "initiate power saving mode")
{
    Taskbar taskbar = new Taskbar();
    taskbar.Show();
    SoundPlayer deacr = new SoundPlayer(Properties.Resources.deacr);
    deacr.PlaySync();
}
else if (speech== "confirm")
{
    SoundPlayer deacd = new SoundPlayer(Properties.Resources.deacd);
    deacd.PlaySync();
    Application.SetSuspendState(PowerState.Suspend, true, true);
}
else if (speech == "cancel")
{
    SoundPlayer cancelled = new SoundPlayer(Properties.Resources.cancelled);
    cancelled.PlaySync();                    
}

请务必在命令txt文档中设置“启动省电模式”和“取消”命令(区分大小写)。

然后,如果您想要保留版本,那么您可以创建一个选项卡式表单并添加自己的自定义命令。希望这可以帮助。但请记住,这是一个让你走过的例子。