Text to speech voice recognition & (TTS) C # Code

  Speech recognition done some time ago, because time is tight, so the Internet to find some code to spend, and found some very complex, and now want to use speech recognition to the Unity project in the past, so they sort out a bit found In fact, Microsoft has given us a good package library. The following is the use of Microsoft's Speech SDK5.1, the database uses MySQL database (MySQL database just contacted yesterday, but it feels good so than SQL Server to be easy to use, speed is not fast, think the general project, then MySQL will be able to cope a)

Interface according to their own design hobby ^ _ ^

 

Add a reference to the main

The following code is attached

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//添加数据库引用
using MySQLDriverCS;
using System.Data.Odbc;
//语音转换引用
using DotNetSpeech;
//using SpeechLib;
//添加语音识别引用
using System.Speech.Recognition;
using System.Threading;
 

namespace SpeechDemo
{
    public partial class Form1 : Form
    {
        //定义语音识别的类
        SpeechRecognizer spr;
        List<string> li;
        public Form1()
        {
            InitializeComponent();
        }
       //private SpeechRecognitionEngine spre;
        private SpVoice voice;
        SpeechVoiceSpeakFlags svsf = SpeechVoiceSpeakFlags.SVSFlagsAsync;
       
        //load加载
        private void Form1_Load(object sender, EventArgs e)
        {
            voice = new DotNetSpeech.SpVoice(); //实例化
            this.txt_text.Text = "";
            this.cmb_type.Text = "中文";
            this.btn_pause.Text = "Pause";
            this.voice.Rate = 0;
            this.voice.Volume = 50;
            Li = this.MySQConnectionMother ();
            this.txt_recive.Focus ();
        }
        // Speech
        Private void btn_speech_Click ( SENDER Object, EventArgs E)
        {
            voice.Speak (this.txt_text.Text, svsf);
            // define a thread to the thread and bound method
        }
        public void btnClick ()
        {
            voice.Speak (this.txt_text.Text, svsf) ;
        }
        // Clear
        Private void btn_clear_Click (SENDER Object, EventArgs E)
        {
            this.txt_text.Text = "";
            this.btn_pause.Text = "Pause";
        }
        // After the volume value is changed event triggered
        Private void tk_voice_ValueChanged (SENDER Object, EventArgs E)
        {
            this.voice.Volume = this.tk_voice.Value;
        }
        // speech rate value changes trigger event
        Private void tk_speed_ValueChanged (SENDER Object, EventArgs E)
        {
            this.voice.Rate = this.tk_speed.Value;
        }
        // start pause &
        Private void btn_pause_Click (SENDER Object, EventArgs E)
        {
            btnClick (this.btn_pause .text);
        }
        Private void btnClick (String BtnText)
        {
            Switch (BtnText)
            {
                Case "Pause":
                 this.voice.Pause ();
                 this.btn_pause.Text = "continue";
                BREAK;
                Case "Continue":
                this.voice.Resume ();
                this.btn_pause.Text = "Pause";
                    BREAK ;
                default:
                    BREAK;
            }
        }
        // generated voice file
        Private void the button1_Click (SENDER Object, EventArgs E)
        {
            the try
            {
                SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "All files (*.*)|*.*|wav files (*.wav)|*.wav";
                sfd.Title = "Save to a wave file";
                sfd.FilterIndex = 2;
                sfd.RestoreDirectory = true;
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
                    SpFileStream SpFileStream = new SpFileStream();
                    SpFileStream.Open(sfd.FileName, SpFileMode, false);
                    voice.AudioOutputStream = SpFileStream;
                    voice.Speak(this.txt_text.Text, SpFlags);
                    voice.WaitUntilDone (Timeout.Infinite);
                    SpFileStream.Close ();
                }
            }
            the catch (Exception)
            {
            }
        }
        // opened dialogue
        Private void the button2_Click (SENDER Object, EventArgs E)
        {
            SpeechRegestion ();
        }
        /// <Summary >
        /// voice recognition
        /// </ Summary>
        Private void SpeechRegestion ()
        {
            SPR new new SpeechRecognizer = (); // provides access and management processes within the speech recognition engine
             GrammarBuilder gramm = new GrammarBuilder (); // set GrammarBuilder
             String [] STRs = null;
             STRs = MakeListTostring (Li);
             eor the Choices Choice new new eor the Choices = (STRs); // definition syntax
              gramm.Append (choice); // add to the gramm
              Grammar gra = new Grammar (gramm) ; //
            spr.LoadGrammarAsync (GRA); // asynchronous loading syntax
            spr.SpeechRecognized + = new EventHandler <SpeechRecognizedEventArgs> (spr_SpeechRecognized); // when the speech recognizer receives the speech recognition to match their occurrence
        }
        voice recognition when // receives its speech recognition to occur when matching
        void spr_SpeechRecognized (Object SENDER, SpeechRecognizedEventArgs E)
        {
            ; String reciveMessage = e.Result.Text.ToString ()
            this.txt_recive.Text = reciveMessage; // grammar recognizer after treatment resulting text
        }

        //连接MySQL数据库
        public List<string> MySQConnectionMother()
        {
          List<string> lis = new List<string>(); ;
           MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("localhost", "speechdb", "root", "admin").AsString);
           try
           {
             conn.Open();//打开数据库
            // MessageBox.Show("数据库已经打开!");
             MySQLCommand comm = new MySQLCommand("select * from sptable",conn);
             MySQLDataReader dr = comm.ExecuteReaderEx();
             
             while (dr.Read())
             {
                 string mm = dr[2].ToString();
                // MessageBox.Show(mm);
                 lis.Add(mm);
             }
           }
           catch (Exception er)
           {
               MessageBox.Show(er.ToString());
           }
           conn.Close();
           conn.Dispose();
           return lis;
        }
        //添加语法到string[] 当中
        public string[]  MakeListTostring(List<string> liststring)
        {
            string[] str = new string[liststring.Count];
            for (int i = 0; i < liststring.Count(); i++)
            {
                str[i] = liststring[i].ToString();
            }
            return str;
        }

        //通过问题得到答案
        public string GetAnswer(string question)
        {
            string answer = null;
           MySQLConnection conn = new MySQLConnection(new MySQLConnectionString("localhost", "speechdb", "root", "admin").AsString);
           try
           {
               conn.Open();
              // MessageBox.Show("数据库又被打开了!");
               MySQLCommand comm = new MySQLCommand();
               comm.CommandText = "select answer from sptable where question='" + question + "'";
               comm.Connection = conn;
               //MessageBox.Show(comm.CommandText);
               if (comm.ExecuteScalar()==null)
               {
                   return null;
               }
               else
               {
                   answer = comm.ExecuteScalar().ToString();
               }
           }
           catch (Exception er)
           {
               MessageBox.Show(er.ToString());              
           }
           conn.Close();
           conn.Dispose();
           return answer;
        }

        void txt_text_TextChanged Private (SENDER Object, EventArgs E)
        {
            voice.Speak (this.txt_text.Text, svsf);
        }
        Private void txt_recive_TextChanged (SENDER Object, EventArgs E)
        {
            ! IF (this.txt_recive.Text.Trim () = null )
            {
               String answer = GetAnswer (this.txt_recive.Text);
               IF (answer = null)!
              {
                this.txt_text.Text = answer;
              }
             the else
             {
                ? this.txt_text.Text = "you said what I did not catch, Please clearly say it again! ";
              }
            }
        }
    }
}

Reproduced in: https: //www.cnblogs.com/Nickzhou/archive/2012/12/21/2827470.html

Guess you like

Origin blog.csdn.net/weixin_34297300/article/details/92850759