但是,這個方法本身並不知道你給的字符串是什麼語言,所以需要我們它這個字符串用什麼語言讀出。SpVoiceClass 類的Voice 屬性就是用來設置語種的,我們可以通過SpVoiceClass 的GetVoices方法得到所有的語種列表,然後在根據參數選擇相應的語種,比如設置語種爲漢語如下所示:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
private void SetChinaVoice()
{
voice.Voice = voice.GetVoices(string.Empty,string.Empty).Item(0) ;
}
0表示是漢用,1234都表示英語,就是口音不同。
這樣,我們就設置了語種,如果結合發音方法,我們就可以設計出一個只發漢語語音的方法
private void SpeakChina(string strSpeak)
{
SetChinaVoice() ;
Speak(strSpeak) ;
}
只發英語語音的方法也是類似的,上面程序裏有。
對於一段中英文混合的語言,我們讓程序讀出混合語音的方法就是:編程把這段語言的中英文分開,對於中文調用SpeakChina方法,英文調用SpeakEnglishi方法;至於怎樣判斷一個字符是英文還是中文,我採用的是判斷asc碼的方法,具體的類方法是通過AnalyseSpeak實現的。
這樣,對於一段中英文混合文字,我們只需把它作爲參數傳遞給AnalyseSpeak就可以了,他能夠完成中英文的混合發音。
當然,對於發音的暫定、繼續、停止等操作,上面也給出了簡單的方法調用,很容易明白。
下面簡單介紹一下中文語音識別的方法:
先把該語音識別的類源代碼貼在下面,然後再做說明:
public class SpRecognition
{
private static SpRecognition _Instance = null ;
private SpeechLib.ISpeechRecoGrammar isrg ;
private SpeechLib.SpSharedRecoContextClass ssrContex =null;
private System.Windows.Forms.Control cDisplay ;
private SpRecognition()
{
ssrContex = new SpSharedRecoContextClass() ;
isrg = ssrContex.CreateGrammar(1) ;
SpeechLib._ISpeechRecoContextEvents_RecognitionEventHandler recHandle =
new _ISpeechRecoContextEvents_RecognitionEventHandler(ContexRecognition) ;
ssrContex.Recognition += recHandle ;
}
public void BeginRec(Control tbResult)
{
isrg.DictationSetState(SpeechRuleState.SGDSActive) ;
cDisplay = tbResult ;
}
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)
{
cDisplay.Text += result.PhraseInfo.GetText(0,-1,true) ;
}
}
我們定義了ssrContex 和isrg爲語音識別的上下文和語法,通過設置isrg的DictationSetState方法,我們可以開始或結束識別,在上面的程序中是BeginRec和CloseRec方法。cDisplay 是我們用來輸出識別結果的地方,爲了能夠在大部分控件上都可以顯示結果,我用了一個Control 類來定義它。當然,每次語音識別後都會觸發ISpeechRecoContextEvents_RecognitionEventHandler 事件,我們定義了一個這樣的方法ContexRecognition來響應事件,並且在這個方法裏輸出識別結果。
這樣,中文語音處理的一些最基本的問題就有了一個簡單的解決方法,當然,這種方法還有很多不完善的地方,希望大家多提出批評意見,共同提高。