基于Window语音识别
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private string Text;
private SpeechRecognitionEngine recognizer;
private DictationGrammar dictationGrammar;
public Form1()
{
InitializeComponent();
string[] a = { };
SRecognition(a,1);
}
private void button1_Click(object sender, EventArgs e)
{
//RecognitionResult result = recognizer.Recognize();
// Console.WriteLine(result.Text);
recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
private void button2_Click(object sender, EventArgs e)
{
recognizer.RecognizeAsyncStop();
}
public void SRecognition(string[] fg, int i) //创建关键词语列表
{
CultureInfo myCIintl = new CultureInfo("zh-CN");
foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers())//获取所有语音引擎
{
Console.WriteLine(config.Culture.EnglishName);
if (config.Culture.Equals(myCIintl))
{
recognizer = new SpeechRecognitionEngine(config);
break;
}//选择识别引擎
}
if (recognizer != null)
{
InitializeSpeechRecognitionEngine(fg);//初始化语音识别引擎
dictationGrammar = new DictationGrammar();
}
else
{
MessageBox.Show("创建语音识别失败");
}
}
void InitializeSpeechRecognitionEngine(string[] s)
{
// Create and load a dictation grammar.
//recognizer.LoadGrammar(new DictationGrammar());
// Configure input to the speech recognizer.
recognizer.SetInputToDefaultAudioDevice();
// Modify the initial silence time-out value.
recognizer.InitialSilenceTimeout = TimeSpan.FromSeconds(5);
GrammarBuilder GB = new GrammarBuilder();
GB.Append("选择");
GB.Append(new Choices(new string[] { "红色", "绿色" }));
Grammar G = new Grammar(GB);
Console.WriteLine(G.RuleName);
G.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(G_SpeechRecognized);
recognizer.LoadGrammar(G);
}
void G_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Text = e.Result.Text;
switch (e.Result.Text)
{
case "选择红色":
BackColor = Color.Red;
button2.BackColor = BackColor;
break;
case "选择绿色":
BackColor = Color.Green;
button2.BackColor = BackColor;
break;
}
}
}
}
添加引用:
image找到system.speech的dll,添加即可
image测试方式:打开电脑麦克风:点击按钮1,然后说选择红色,或者选择绿色即可,代码只是简单测试的,后面有什么可以自己扩展。
转载 (110条消息) C#调用window语音识别_纸上得来终觉浅,绝知此事要躬行-CSDN博客_c# windows 语音识别
网友评论