您的位置:首页 > 编程语言 > C#

C#调用SAPI实现语音识别的两种方法

2014-11-11 10:55 169 查看
通过微软的SAPI,不仅仅可以实现语音合成TTS,同样可以实现语音识别SR。下面我们就介绍并贴出相关代码。主要有两种方式:

1、使用COM组件技术,不管是C++,C#,Delphi都能玩的转,开发出来的东西在XP和WIN7都能跑。(注意要引入系统组件SpeechLib,XP要安装识别引擎)

2、使用WIN7的windows api,其实最终还是调用了SAPI,所以开发出来的东西就只能在WIN7上面跑。

其实不管是哪一种,都是调用SAPI,可能后一种代码比较简单。

使用第一种方式,需要注意在COM选项卡里面的Microsoft Speech object library引用

最近打算研究一下语音识别,但是发现网上很少有C#的完整代码,就把自己的学习心得放上来,和大家分享一下。

下载API:

1)SpeechSDK51.exe (67.0 MB)

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

作者:Cosmokey来自:http://www.cnblogs.com/comsokey

出处:http://www.cnblogs.com/comsokey

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。来自:http://www.cnblogs.com/comsokey
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: