我是 C# 新手,要学习,我正在观看并尝试网络上的示例。
我看到了这个例子:
using System;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Speech.Recognition;
namespace MouseController
{
public partial class Form1 : Form
{
SpeechRecognitionEngine recognitionEngine;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Initialize();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
recognitionEngine.RecognizeAsyncStop();
}
private void Initialize()
{
recognitionEngine = new SpeechRecognitionEngine();
recognitionEngine.SetInputToDefaultAudioDevice();
recognitionEngine.SpeechRecognized += (s, args) =>
{
string line = "";
foreach (RecognizedWordUnit word in args.Result.Words)
{
if (word.Confidence > 0.5f)
line += word.Text + " ";
}
string command = line.Trim();
switch (command)
{
case "left":
MoveMouse(Cursor.Position.X - 50, Cursor.Position.Y);
break;
case "right":
MoveMouse(Cursor.Position.X + 50, Cursor.Position.Y);
break;
case "up":
MoveMouse(Cursor.Position.X, Cursor.Position.Y - 50);
break;
case "down":
MoveMouse(Cursor.Position.X, Cursor.Position.Y + 50);
break;
}
txtOutput.Text += line;
txtOutput.Text += Environment.NewLine;
};
recognitionEngine.UnloadAllGrammars();
recognitionEngine.LoadGrammar(CreateGrammars());
recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
}
private Grammar CreateGrammars()
{
Choices commandChoices = new Choices("left", "right", "up", "down");
GrammarBuilder grammarBuilder = new GrammarBuilder();
grammarBuilder.Append(commandChoices);
return new Grammar(grammarBuilder);
}
private void MoveMouse(int x, int y)
{
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(x, y);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
}
}
但是当我说“上”、“下”、“左”或“右”时,什么也没有发生……
我也试过这个:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Speech.Recognition;
namespace SpeechRecognitionExample
{
public partial class Form1 : Form
{
private SpeechRecognitionEngine recognitionEngine;
public Form1()
{
InitializeComponent();
recognitionEngine = new SpeechRecognitionEngine();
recognitionEngine.SetInputToDefaultAudioDevice();
recognitionEngine.SpeechRecognized += (s, args) =>
{
foreach (RecognizedWordUnit word in args.Result.Words)
{
if (word.Confidence > 0.8f)
txtOutput.Text += word.Text + " ";
}
txtOutput.Text += Environment.NewLine;
};
recognitionEngine.LoadGrammar(new DictationGrammar());
}
private void btnStart_Click(object sender, EventArgs e)
{
recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
}
private void btnStop_Click(object sender, EventArgs e)
{
recognitionEngine.RecognizeAsyncStop();
}
}
}
而且它不起作用...
在这两个代码中,我都没有从 Visual Studio 中得到任何错误。
为什么它不起作用?
我检查了我的麦克风,它正在工作。