2017-02-17 11 views
2

그래서 기본적으로 두 개의 음성 인식 엔진 (speechrecog & speechrecog1)과 하나의 음성 합성기를 사용했습니다. speechrecog에 질문이있을 때 답장을 보내면 컴퓨터가 두 숫자 1,2 중에서 2 개를 선택합니다. 그런 다음 두 번째 음성 인식 엔진을 초기화합니다. 그 일을 할 때. 그런 다음 두 번째 버튼을 끄고 첫 번째 버튼을 다시 켜십시오. 그러나 문제는 두 번째 음성 인식 엔진을 사용할 때 (음성 합성기) 두 번째 음성 인식 엔진을 다시 시도한 횟수입니다. you.txt 포함 얼마나 텍스트 파일 : 예를 들어음성 합성기 자체를 반복하는 것을 어떻게 수정합니까?

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(); 
     } 

    } 
} 

: 다음은 그 형태에 대한 내 코드의 난 괜찮아요. 고맙습니다. 당신은 얼마나 좋은 # 좋은 # 나쁜 # 이며, 컴퓨터가 좋은지 묻는다면 나는 좋은 대답. good.txt 파일에서 : 아 멋지다.

나는 그녀에게 처음 : 너 어떠니?

답장 : 나는 잘됐다. 좋은

응답 : 당신은 어떻게

사용자의 아 그게 쿨 (1 시간)

나는 그녀에게 2 시간 : 당신이 얼마나 있습니까?

답장 : 나는 잘됐다. 좋은

응답 : 당신은 어떻게

사용자 인 당신이 어떻게 있습니다 : 아 그게 시원한

내가 그녀를 물어 3 시간 (이 2 회 반복)?

답장 : 나는 잘됐다.

응답 좋은 : 어떻게 당신

사용자의 아 그게 멋진 내가 반복 문제를 해결하려면 어떻게

(그것을 반복 3 회).

+1

Theres 많이 여기에, 당신은 문제를 일으키는 방법을 좁힐 수 있습니까? 먼저 음성 신디사이저 중 하나를 비활성화하고 거기에서부터 시도하십시오. –

+0

@ 릭 제임스 그건 내 실수를 분리하려고했지만 문제가 어디로 잘못 갔는지 알 수 없다. btw 단 하나의 음성 신디사이저가 있습니다 –

+0

중단 점을 설정하고 밟았습니까? –

답변

0

@ Niikolay Shmyrev 덕분에 해결책을 찾았습니다. 그가 말했듯이 내 이벤트 핸들러가 두 번 해고되었다. 그래서 내부에 넣어 :

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