c# 語音識別 | 智能對話


在.NET4.0中,我可以借助System.Speech組件讓電腦來識別我們的聲音。

 

 

 

 

 

以上,當我說"name",顯示"Darren",我說"age",顯示"永遠21"。如何做呢?


首先要開啟電腦的語音識別功能。


右鍵電腦右下方的揚聲器,選擇"錄音設備"。


點擊默認的"麥克風",再點擊左下角的"配置"按鈕。

 

 

在VS中創建一個窗體應用程序,界面上有一個RichTextBox和2個Button。


添加System.Speech的引用。

 (PS:強調一下如果不打開語音識別功能,啟動程序會報錯:在此系統上語音識別不可用。找不到 SAPI 和語音識別引擎。)

編寫如下:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Speech.Recognition;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsForms
{
    public partial class Form1 : Form
    {
        SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();
        public Form1()
        {
            InitializeComponent();
        }

        private void btnEnable_Click(object sender, EventArgs e)
        {

            recEngine.RecognizeAsync(RecognizeMode.Multiple);
            btnDisable.Enabled = true;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Choices preCmd = new Choices();
            preCmd.Add(new string[] { "name", "age" });

            GrammarBuilder gb = new GrammarBuilder();
            gb.Append(preCmd);
            Grammar gr = new Grammar(gb);
            recEngine.LoadGrammarAsync(gr);
            recEngine.SetInputToDefaultAudioDevice();
            recEngine.SpeechHypothesized += RecEngine_SpeechHypothesized;


        }

        private void RecEngine_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
        {
            switch (e.Result.Text)
            {
                case "name":
                    txtList.Text += "\nDarren";
                    break;
                case "age":
                    txtList.Text += "\n永遠21";
                    break;
                default:
                    break;
            }
        }

        private void btnDisable_Click(object sender, EventArgs e)
        {
            recEngine.RecognizeAsyncStop();
            btnDisable.Enabled = false;
        }
    }
}

 

當然中文也是可以識別的,項目很有意思,大家可以調用語音播放進行播放回復內容。

以上內容轉載於:https://www.cnblogs.com/darrenji/p/4373664.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM