C# 语音识别(文字to语音、语音to文字)
最近打算研究一下语音识别,但是发现网上很少有C#的完整代码,就把自己的学习心得放上来,和大家分享一下。
下载API:
2)SpeechSDK51LangPack.exe (81.0 MB)
API可以不下载,但是如果你的VS是英文版,但是想使用中文的语音,那你就需要下载API,按顺序安装好。
(PS:我的VS是英文的,不能说中文,为了这个我纠结了一上午。API下载地址,感谢:XAF ,http://smartsoft.5d6d.com/thread-8819-1-1.html)
文字to语音:
这个相当的简单。
1)在COM选项卡里面的Microsoft Speech object library引用
2)using SpeechLib;
3)SpVoiceClass voice = new SpVoiceClass();//SAPI 5.1
SpVoice voice = new SpVoice();//SAPI 5.4
4)voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(3);
5)voice.Speak(“你要说的话”);
PS:在第四步的时候是选择语言,不同API可能不一样,网上有说是0,但是我使用的API却是3。
语音to文字:
public class SpRecognition { private static SpRecognition _Instance = null; private SpeechLib.ISpeechRecoGrammar isrg; private SpeechLib.SpSharedRecoContextClass ssrContex = null;
public delegate void StringEvent(string str); public StringEvent SetMessage;
private SpRecognition() { ssrContex = new SpSharedRecoContextClass(); isrg = ssrContex.CreateGrammar(1); SpeechLib._ISpeechRecoContextEvents_RecognitionEventHandler recHandle = new _ISpeechRecoContextEvents_RecognitionEventHandler(ContexRecognition); ssrContex.Recognition += recHandle; } public void BeginRec() { isrg.DictationSetState(SpeechRuleState.SGDSActive); } public static SpRecognition instance() { if (_Instance == null) _Instance = new SpRecognition(); return _Instance; } public void CloseRec() { isrg.DictationSetState(SpeechRuleState.SGDSInactive); } private void ContexRecognition(int iIndex, object obj, SpeechLib.SpeechRecognitionType type, SpeechLib.ISpeechRecoResult result) { if (SetMessage != null) { SetMessage(result.PhraseInfo.GetText(0, -1, true)); } } }
希望上面代码对大家有用。s