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,每次当列表方法需要用户输入时,我都必须按Enter键,写sg,然后再次按Enter键。似乎还有另一个控制台。ReadLine()在每个控制台之前。'list'方法中的ReadLine()。
ears.stop()只会停止语音识别。
Map是一个类,包含2个字符串(值、键)。
我有点困惑。知道吗?