定義 private SpeechLib.SpVoiceClass voice = null;,首次調用時以 BuildSpeach 初始化。定義 Volume、Rate 屬性設定音量與語速。
private void Speak(string strSpeack)
{
try
{
voice.Speak(strSpeack, SpeechVoiceSpeakFlags.SVSFlagsAsync); // 非同步發音
}
catch (Exception err)
{
throw new Exception("發生一個錯誤:" + err.Message);
}
}
SpVoiceClass 不知字串語言,需透過 Voice 屬性設定。用 GetVoices 取得語種清單,選擇對應項目:
private void SetChinaVoice()
{
voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0); // 0 為中文
}
private void SetEnglishVoice()
{
voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(1); // 1 為英文
}
索引 0 為中文,1、2、3、4 為不同口音英文。
SpeakChina,英文呼叫 SpeakEnglish。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 為辨識上下文與語法。DictationSetState 控制啟動/停止辨識(SGDSActive/SGDSInactive)。cDisplay 為輸出控制項,用 Control 型別支援多種控制項。Recognition 事件觸發 ContexRecognition 回應,輸出辨識文字。這為中文語音處理基本問題提供簡單解決方案,仍有改進空間,歡迎批評指教共同精進。