C#中的System.Speech命名空间初探
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中的System.Speech命名空间初探相关的知识,希望对你有一定的参考价值。
本程序是口算两位数乘法,随机生成两个两位数,用语音读出来。然后开启语音识别,接受用户输入,知道答案正确关闭语音识别。用户说答案时,可以说“再说一遍”重复题目。
关键是GrammarBuilder和Choices的用法。
首先来看看如何获得已安装的语音识别引擎
void showInstalled() { Console.WriteLine("installed recognizers"); foreach (var i in SpeechRecognitionEngine.InstalledRecognizers()) { Console.WriteLine(String.Format("{0}\t{1}\t{2}\t{3}\n", i.Id, i.Name, i.Culture, i.Description)); } }
下面是主程序
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Speech; using System.Speech.Recognition; using System.Globalization; using System.Windows.Forms; using System.Speech.Synthesis; public class Haha { static void Main() { new Haha(); } SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(); int x, y, z; SpeechSynthesizer cout = null; Haha() { recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized); recognizer.SetInputToDefaultAudioDevice(); String s = "0"; for (int i = 1; i <= 9; i++) s += " " + i; GrammarBuilder num = new GrammarBuilder(new Choices(s.Split(new char[] { ‘ ‘ }))); num = new GrammarBuilder(num, 1, 4); Choices all = new Choices(); all.Add(num); all.Add("再说一遍"); recognizer.LoadGrammarAsync(new Grammar(all)); run(); } void run() { cout = new SpeechSynthesizer(); Random random = new Random(); while (true) { x = random.Next(11, 99); y = random.Next(11, 99); z = -1; cout.Speak(x + "成以" + y); recognizer.RecognizeAsync(RecognizeMode.Multiple); while (true) { if (z != -1) { if (z == x * y) { cout.Speak("正确,真聪明"); break; } else { cout.Speak(String.Format("不是{0},再算!",z)); z = -1; } } } recognizer.RecognizeAsyncStop(); } } void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string text = e.Result.Text; Console.WriteLine(text); if (text == "再说一遍") { cout.Speak(x + "成以" + y); return; } try { z = int.Parse(text); } catch { z = -1; } } }
以上是关于C#中的System.Speech命名空间初探的主要内容,如果未能解决你的问题,请参考以下文章
C#的winform程序,引用了system.speech.dll,在本地win7,32机器正常运行,64位就报错
C# System.Speech.dll 实现语音播报无需联网
C# System.Speech.dll 实现语音播报无需联网