一个基于c#3.0的开发基于vista下语音识别的通用类

废话少说,看代码精解,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech;
using System.Speech.Synthesis;
using System.Speech.Recognition;
using System.Globalization;
using System.Windows.Forms;

namespace [email protected]
{
public class yuyin
{
public SpeechRecognitionEngine recognizer = null;
public DictationGrammar dictationGrammar = null;
public System.Windows.Forms.Control cDisplay;


public yuyin(string[] fg)//创建关键词语列表
{

CultureInfo myCIintl = new CultureInfo("zh-CN", false);


foreach (RecognizerInfo config in SpeechRecognitionEngine.InstalledRecognizers())//获取所有语音引擎
{
if (config.Culture.Equals(myCIintl) && config.Id == "MS-2052-80-DESK")//选择中文
{
recognizer = new SpeechRecognitionEngine(config);
break;
}

}
if (recognizer != null)
{

InitializeSpeechRecognitionEngine(fg);
dictationGrammar = new DictationGrammar();
}
else
{
MessageBox.Show("创建语音识别失败");

}


}

private void InitializeSpeechRecognitionEngine(string[] fg)
{
recognizer.SetInputToDefaultAudioDevice();
Grammar customGrammar = CreateCustomGrammar(fg);
recognizer.UnloadAllGrammars();
recognizer.LoadGrammar(customGrammar);
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized);
}
public void BeginRec(Control tbResult)//关联窗口控件
{

TurnSpeechRecognitionOn();
TurnDictationOn();
cDisplay = tbResult;
}
public void over()
{

TurnSpeechRecognitionOff();

}
public virtual Grammar CreateCustomGrammar(string[] fg)
{
GrammarBuilder grammarBuilder = new GrammarBuilder();
grammarBuilder.Append(new Choices(fg));
return new Grammar(grammarBuilder);
}

private void TurnSpeechRecognitionOn()
{
if (recognizer != null)
{
recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
else
{
MessageBox.Show("创建语音识别失败");

}

}

private void TurnSpeechRecognitionOff()
{
if (recognizer != null)
{
recognizer.RecognizeAsyncStop();

TurnDictationOff();
}
else
{
MessageBox.Show("创建语音识别失败");

}

}
private void recognizer_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
{

}

private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string text = e.Result.Text;
cDisplay.Text = text;

}
private void TurnDictationOn()
{
if (recognizer != null)
{
recognizer.LoadGrammar(dictationGrammar);
}
else
{
MessageBox.Show("创建语音识别失败");

}

}

private void TurnDictationOff()
{
if (dictationGrammar != null)
{
recognizer.UnloadGrammar(dictationGrammar);
}
else
{
MessageBox.Show("创建语音识别失败");

}
}

}
}

类的调用

string[] fg = {“东方”,“西方”,“南方”,“北方” };
qqq = new yuyin(fg);

qqq.BeginRec(textBox10); 显示识别的信息的控件

需要源码的请留下EMAIL


你可能感兴趣的:(C++,c,windows,C#,LINQ)