使用语音识别库编写和关闭记事本

时间:2017-11-13 10:13:34

标签: c# speech-recognition voice-recognition

我试着写一个代码,它可以打开一个Notepad ++,但问题是我遇到了这个问题,我想在记事本中写一些东西然后关闭它。以下是我的代码。我对c#完全陌生,是否有任何图书馆或方法可以做到这一点?

请欣赏任何输入

    // Button Reference
private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text.Equals("Enable Voice Control"))
    {
        button1.Text = "Stop Voice Control";
        recEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
    else
    {
       button1.Text = "Enable Voice Control";
        recEngine.RecognizeAsyncStop();
    }

}



public void Form1_Load(object sender, EventArgs e)
{
    Choices commands = new Choices();
    commands.Add(myCommands);
    GrammarBuilder gBuilder = new GrammarBuilder();
    gBuilder.Append(commands);
    Grammar grammar = new Grammar(gBuilder);

    recEngine.LoadGrammarAsync(grammar);
    recEngine.SetInputToDefaultAudioDevice();
    recEngine.SpeechRecognized += recEngine_SpeechRecognized;

}
void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
            Process cmd = new Process();
            cmd.StartInfo.FileName = @"notepad++.exe" ;
        //    cmd.StartInfo.Arguments =@"\Write.txt";
            cmd.Start();
            cmd.CloseMainWindow();
            cmd.WaitForExit();
            cmd.Refresh();

        //  if (cmd.StandardError != null)
        // Console.WriteLine(cmd.StandardError.ReadToEnd());


        var result = e.Result;
            var i = 0;
    foreach (var command in myCommands)
    {

            if (command.StartsWith("close"))
                {
                this.Close();
          //      cmd.StartInfo.FileName = @"notepad++";
                cmd.Kill();
            }
        if (command.StartsWith("--") || command == string.Empty) continue;  // Skip commentBlocks and skipEmptylines
            var parts = command.Split(new char[] { '|' }); // Split the lines
                   i++;
        if (command.Equals(result.Text))
        {
            Console.WriteLine("Command is  {0}: {1}", i, command);
            break;
        }
    }
}

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
    }
}

}

2 个答案:

答案 0 :(得分:0)

您无需打开记事本并写入文件。你可以用程序化的方式来做。

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);

答案 1 :(得分:-1)

您可以使用以下代码关闭记事本:

Process[] processes = Process.GetProcessesByName("notepad");
foreach (var process in processes)
{
    process.Kill();
}

它会关闭记事本的所有实例。所以最好确保记事本只是你的记事本(由你的语音识别程序打开)

如果您实际上不想打开记事本,并且您的要求只是捕获文本并以编程方式写入文件,请使用以下代码:

// Create a file to write to.
string createText = "Hello World"; // Replace with voice captured text
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);