如何修复语音合成器重复c#?

时间:2017-02-17 20:44:01

标签: c# speech-recognition repeat speech-synthesis

所以基本上我使用了两个语音识别引擎(speechrecog& speechrecog1)和一个语音合成器。当语音识别被问到一个问题,比如你是怎么回事 然后它回复我很好(如果计算机从两个数字1,2中选择2)。然后它初始化第二个语音识别引擎。什么时候做它的东西。然后关闭第二个,再打开第一个。但问题是当使用第二个语音识别引擎时,它重复(语音合成器)我尝试第二个语音识别引擎的次数。 这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
namespace Project_Juliet
{
    public partial class Form11 : Form
    {
        public Form11()
        {
            InitializeComponent();
        }
        class FullScreen
        {
            public void EnterFullScreenMode(Form targetForm)
            {
                targetForm.WindowState = FormWindowState.Normal;
                targetForm.FormBorderStyle = FormBorderStyle.None;
                targetForm.WindowState = FormWindowState.Maximized;
            }

            public void LeaveFullScreenMode(Form targetForm)
            {
                targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
                targetForm.WindowState = FormWindowState.Normal;
            }
        }


       // System.Globalization.CultureInfo cl2 = new System.Globalization.CultureInfo("en-US");

        SpeechRecognitionEngine speechrecog = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
        SpeechSynthesizer ss = new SpeechSynthesizer();
        PromptBuilder pb = new PromptBuilder();
        Choices zlist = new Choices();
        Form2 frm = new Form2();
        FullScreen fs = new FullScreen();
        bool SpeechRecognitionState = true;
        Choices dirlist = new Choices();
        SpeechRecognitionEngine speechrecog1 = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
        bool sprs2 = false;
        Choices us = new Choices();
        string dir234;
        string[] gm;



        private void Form11_Load(object sender, EventArgs e)
        {

            listBox1.Visible = false;
            string dir = "C:/Users/" + Environment.UserName + "/Documents/Juliet/response";
            DirectoryInfo dinfo = new DirectoryInfo(dir);
            FileInfo[] Files = dinfo.GetFiles("*.txt");
            webBrowser1.ScriptErrorsSuppressed = true;



            foreach (FileInfo file2 in Files)
            {
                string yts = ".txt";

                listBox1.Items.Add(file2.Name.Replace(yts + "", ""));
            }
           /* String[] list = new String();
            list = listBox1.Items.OfType<string>().ToList();
            */




           fs.EnterFullScreenMode(this);
           textBox1.Width = toolStrip1.Width - 10;
           // toolStripTextBox1.Width = toolStrip1.Width - 30;
           // toolStripTextBox1.Select();
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Teen);
            zlist.Add(new string[] { "exit"});
            Grammar gr = new Grammar(new GrammarBuilder(zlist));
            gr.Weight = 0.9f;

            dirlist.Add(new string[]{"Mr.Danely"});

            foreach (FileInfo file2 in Files)
            {
                string yts = ".txt";

                dirlist.Add(file2.Name.Replace(yts + "", ""));
            }
            Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
            gr1.Weight = 1f;
            Grammar tgi = new DictationGrammar();
            tgi.Weight = 0.3f;
            try
            {

                if (SpeechRecognitionState == true)
                {
                    speechrecog.RequestRecognizerUpdate();
                    speechrecog.LoadGrammar(gr);
                    speechrecog.LoadGrammar(gr1);
                    speechrecog.LoadGrammar(tgi);
                    speechrecog.SpeechRecognized += speechrecog_SpeechRecognized;
                    speechrecog.SetInputToDefaultAudioDevice();
                    speechrecog.RecognizeAsync(RecognizeMode.Multiple);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }

            //us.Add(new string[] { "yes","no","good","bad" });
            us.Add(new string[] { "exit" });
            Grammar gr12 = new Grammar(new GrammarBuilder(us));
            if (sprs2 == true)
            {

            }

        }

        void speechrecog1_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {


           if(File.Exists(@"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//"+e.Result.Text.ToString()+".txt"))
           {

               string hjjk = @"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//" + e.Result.Text.ToString() + ".txt";
                          StreamReader file = new StreamReader(hjjk);
                          string readText = file.ReadLine();
                          file.Close();
                          ss.Speak(readText);
                          timer2.Interval = 10;
                          timer2.Start();

           }

          }



          void speechrecog_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
          {
              string igput = e.Result.Text.ToString();
              dir234 = @"C://Users//" + Environment.UserName + "//Documents//Juliet//response//" + igput + ".txt";
              if (igput == "exit")
              {

                  speechrecog.RecognizeAsyncStop();
                  this.Hide();

                  frm.Closed += (s, args) => this.Close();
                  frm.Show();
              }
              else
              {
                  if (File.Exists(dir234))
                  {
                      StreamReader file = new StreamReader(dir234);
                      string readText = file.ReadLine();
                      file.Close();
                      if (readText.Contains("%"))
                      {
                          string[] words = readText.Split('%');
                          Random r = new Random();
                          int selection = r.Next(1, 3);

                          if (selection == 1)
                          {

                              ss.SpeakAsync(words[0]);
                          }
                          if (selection == 2)
                          {

                              if (readText.Contains('#'))
                              {
                                  SpeechRecognitionState = false;
                                  us.Add(new string[] { "exit" });
                                  gm = words[1].Split('#');
                                  string speak = words[0] + gm[0];
                                  ss.SpeakAsync(speak);
                                  List<string> lk = gm.ToList();
                                  lk.RemoveAt(0);
                                  string[] hkl = lk.ToArray<string>();
                                  foreach(string g3 in hkl)
                                  {
                                      if (g3.Contains(".txt"))
                                      {
                                          string fj = g3.Replace(".txt" + "", "");
                                          us.Add(fj);
                                      }
                                      else
                                      {
                                          string fj = g3;
                                          us.Add(fj);


                                      }
                                  }

                                  string dir333 = @"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1";
                                  Grammar gr12 = new Grammar(new GrammarBuilder(us));


                                  try
                                  {
                                      speechrecog1.RequestRecognizerUpdate();
                                      speechrecog1.LoadGrammar(gr12);
                                      speechrecog1.SpeechRecognized += speechrecog1_SpeechRecognized;
                                      speechrecog1.SetInputToDefaultAudioDevice();
                                      speechrecog1.RecognizeAsync(RecognizeMode.Single);
                                      //speechrecog1.RecognizeAsyncStop();
                                      //speechrecog.RecognizeAsync(RecognizeMode.Multiple);
                                      //_completed.WaitOne(); // wait until speech recognition is completed




                                  }
                                  catch (Exception ex)
                                  {
                                      MessageBox.Show(ex.Message, "Error");
                                  }

                                 // timer2.Interval = 7000;
                                  //timer2.Start();

                                 // timer2.Interval = 5000;
                                  //timer2.Start();



                              }
                              else

                              {
                                  string speak = words[0] + words[1];
                                  ss.SpeakAsync(speak);
                              }

                          }

                      }
                      else
                      {
                          ss.Speak(readText);
                      }
                  }
                  else

                  {
                      try
                      {
                          tabControl1.SelectedIndex = 1;
                          webBrowser1.Navigate("https://www.google.com/search?q=" + e.Result.Text.ToString());
                      }
                      catch (Exception ex)
                      {
                          string ggh = "Error"+ex;
                      }
                  }
              }
              /* SpeechRecognitionState = false;
               timer1.Interval = 3000;
                timer1.Start();
               *  */
            textBox1.Text = "You: "+e.Result.Text.ToString();

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            SpeechRecognitionState = true;
            timer1.Stop();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void timer2_Tick(object sender, EventArgs e)
        {
             //loading the grammar again somehow make the recognition better
           speechrecog.UnloadAllGrammars();
        Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
        gr1.Weight = 1f;
        Grammar tgi = new DictationGrammar();
        tgi.Weight = 0.3f;
        Grammar gr = new Grammar(new GrammarBuilder(zlist));
        gr.Weight = 0.9f;
        speechrecog.LoadGrammar(gr);
        speechrecog.LoadGrammar(gr1);
        speechrecog.LoadGrammar(tgi);
            SpeechRecognitionState = true;
            speechrecog1.RecognizeAsyncStop();

            speechrecog1.UnloadAllGrammars();

            timer2.Stop();
        }

    }
}

例如:     文本文件you.txt如何包含:     我很好。谢谢。%你好#好#坏 并且计算机询问我是否良好并且我回复良好。在good.txt文件中: 哦,那太酷了

我第一次问她:你好吗?

回复:我很好。你好吗

用户:好

回复:哦,那很酷(1次)

我第二次问她:你好吗?

回复:我很好。你好吗

用户:好

回复:哦,那很酷(重复2次)

我第三次问她:你好吗?

回复:我很好。你好吗

用户:好

回复:哦,那很酷(重复3次)

如何解决重复问题。

1 个答案:

答案 0 :(得分:0)

感谢@Nikolay Shmyrev我找到了解决方案。正如他所说,我的事件处理程序是两次开火。所以在里面我放了一个:

try
{
    //My code
}
finally
{
    speechrecog1.SpeechRecognized -= speechrecog1_SpeechRecognized;
}