之前在一次面试中,面试官事先发来一份面试题,其中有一题是输入一段文字,使其发出声音。当时看到此题,第一反应是需要调用WINDOWS底层API,后来想到.net类库如此强大,说不准有。之后网上搜索一下发现果不其然,现在分享给大家。首先,需要下载API:
1)SpeechSDK51.exe (67.0 MB)
2)SpeechSDK51LangPack.exe (81.0 MB)
文字→语音:
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("你要说的话");
语音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));
}
}
|
|