首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

語音合成與辨識技術在 C# 中的應用 (2):中英文混合朗讀與語音辨識實作

     編輯:關於C語言

核心發音類別與屬性

定義 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。
  • 判斷字元為中文或英文:採用 ASCII 碼判斷(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 回應,輸出辨識文字。

這為中文語音處理基本問題提供簡單解決方案,仍有改進空間,歡迎批評指教共同精進。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved