コード例 #1
1
ファイル: frmSettings.cs プロジェクト: NotYours180/AVPI
        private void populate_fields()
        {
            List<String> localizations = new List<String>();
            foreach (RecognizerInfo ri in SpeechRecognitionEngine.InstalledRecognizers())
            {
                localizations.Add(ri.Culture.Name);
            }
            cbSettingsLanguage.DataSource = localizations;

            List<String> voices = new List<string>();
            SpeechSynthesizer synthesizer = new SpeechSynthesizer();
            foreach (InstalledVoice voice in synthesizer.GetInstalledVoices())
            {
                voices.Add(voice.VoiceInfo.Name);
            }
            cbSettingsSynthesizer.DataSource = voices;

            List<string> audio_devices = new List<string>();

            //TODO: actually enumerate audio devices.
            audio_devices.Add("Default Directsound device");

            cbSettingsRecordingDevice.DataSource = audio_devices;

            List<string> pushtotalk_mode_list = new List<string>();
            pushtotalk_mode_list.Add("Off");
            pushtotalk_mode_list.Add("Hold");
            pushtotalk_mode_list.Add("PressOnce");
            cbSettingsPushToTalkMode.DataSource = pushtotalk_mode_list;
            cbSettingsPushToTalkMode.SelectedItem = vi_settings.pushtotalk_mode;

            cbSettingsPushToTalkKey.DataSource = Enum.GetValues(typeof(Keys)).Cast<Keys>();
            cbSettingsPushToTalkKey.SelectedItem = Enum.Parse(typeof(Keys), vi_settings.pushtotalk_key);

        }
コード例 #2
0
ファイル: Form1.cs プロジェクト: rhpa23/TTSrecorder
        private void Form1_Load(object sender, EventArgs e)
        {
            IList<VoiceInfo> voiceInfos = new List<VoiceInfo>();
            var reader = new SpeechSynthesizer();

            var installedVoices = reader.GetInstalledVoices();
            if (installedVoices.Count == 0)
            {
                MessageBox.Show(this,
                    "Your system don't have a 'Text to Speech' to make this work. Try install one for continue.",
                    "Finish", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            else
            {
                foreach (InstalledVoice voice in installedVoices)
                {
                    voiceInfos.Add(voice.VoiceInfo);
                }
                cmbVoice.DataSource = voiceInfos;
                cmbVoice.DisplayMember = "Name";
                cmbVoice.ValueMember = "Id";
            }
            reader.Dispose();
        }
コード例 #3
0
ファイル: Synthesizer.cs プロジェクト: DenprogIS/Charles
 public void Synthes(string textToSpeech)
 {
     SpeechSynthesizer ss = new SpeechSynthesizer();
     var voiceList = ss.GetInstalledVoices();
     ss.SelectVoice(voiceList[2].VoiceInfo.Name); //[0,1] - std english synthesizers, [2] - Nikolay
     ss.Volume = 100; // от 0 до 100
     ss.Rate = 0; //от -10 до 10
     ss.SpeakAsync(textToSpeech);
 }
コード例 #4
0
 public static IEnumerable<string> GetVoices()
 {
     using (var synthesizer = new SpeechSynthesizer())
     {
         var installedVoices = synthesizer.GetInstalledVoices();
         var voices = installedVoices.Where(voice => voice.Enabled);
         return voices.Select(voice => voice.VoiceInfo.Name);
     }
 }
コード例 #5
0
ファイル: SpeechScope.cs プロジェクト: thomas-parrish/Common
        public SpeechScope(VoiceInfo voiceInfo, params string[] phrases)
        {
            _phrases = phrases;
            _synth = new SpeechSynthesizer();

            _synth.SelectVoice(voiceInfo != null
                ? voiceInfo.Name
                : _synth.GetInstalledVoices()
                    .Where(v => v.VoiceInfo.Culture.Equals(CultureInfo.CurrentCulture))
                    .RandomElement().VoiceInfo.Name);
        }
コード例 #6
0
 public TextToSpeechWindows()
 {
     try
     {
         speechSynthesizer = new SpeechSynthesizer();
         voices = speechSynthesizer.GetInstalledVoices();
     }
     catch (Exception ex)
     {
         Trace.TraceError("voice synthetizer failed: {0}", ex);
     }
 }
コード例 #7
0
ファイル: SapiTTS.cs プロジェクト: 3DI70R/SpeechSequencerCore
        public static string[] GetAllVoices()
        {
            List<string> voices = new List<string>();
            SpeechSynthesizer synth = new SpeechSynthesizer();

            foreach (InstalledVoice voice in synth.GetInstalledVoices())
            {
                voices.Add(voice.VoiceInfo.Name);
            }

            return voices.ToArray();
        }
コード例 #8
0
ファイル: TextToSpeech.cs プロジェクト: Morphan1/Voxalia
 public static void Speak(string text, bool male)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
     #if WINDOWS
             if (TrySpeech)
             {
                 SpeechSynthesizer speech = new SpeechSynthesizer();
                 VoiceInfo vi = null;
                 foreach (InstalledVoice v in speech.GetInstalledVoices())
                 {
                     if (!v.Enabled)
                     {
                         continue;
                     }
                     if (vi == null)
                     {
                         vi = v.VoiceInfo;
                     }
                     else if ((male && v.VoiceInfo.Gender == VoiceGender.Male) || (!male && v.VoiceInfo.Gender == VoiceGender.Female))
                     {
                         vi = v.VoiceInfo;
                         break;
                     }
                 }
                 if (vi == null)
                 {
                     TrySpeech = false;
                 }
                 else
                 {
                     speech.SelectVoice(vi.Name);
                     speech.Speak(text);
                 }
             }
     #endif
             TrySpeech = false;
         }
         catch (Exception ex)
         {
             Utilities.CheckException(ex);
             TrySpeech = false;
         }
         if (!TrySpeech)
         {
             String addme = male ? " -p 40" : " -p 95";
             Process p = Process.Start("espeak", "\"" + text.Replace("\"", " quote ") + "\"" + addme);
             Console.WriteLine(p.MainModule.FileName);
         }
     });
 }
コード例 #9
0
 public ChatToSpeech(Spring spring)
 {
     try
     {
         speechSynthesizer = new SpeechSynthesizer();
         voices = speechSynthesizer.GetInstalledVoices();
         spring.LogLineAdded += spring_LogLineAdded;
     }
     catch (Exception ex)
     {
         Trace.TraceError("voice synthetizer failed: {0}", ex);
     }
 }
コード例 #10
0
 private IEnumerable<InstalledVoice> GetInstalledVoices()
 {
     using (var synth = new SpeechSynthesizer())
     {
         var installedVoices = synth.GetInstalledVoices();
         Debug.WriteLine("Installed voices -");
         foreach (InstalledVoice voice in installedVoices)
         {
             VoiceInfo info = voice.VoiceInfo;
             Debug.WriteLine(" Voice Name: {0} Culture: {1}", info.Name, info.Culture);
         }
         return installedVoices.ToList();
     }
 }
        public ActionResult Post(IEnumerable<VoiceMessage> voiceMessage)
        {


            // Initialize a new instance of the SpeechSynthesizer.
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {

                //    // Output information about all of the installed voices. 
                //    Console.WriteLine("Installed voices -");
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    VoiceInfo info = voice.VoiceInfo;
                    Console.WriteLine(" Voice Name: " + info.Name);
                }
            } 

            
            
            string toBeVoiced =  string.Empty;
            try
            {
                foreach (var voice in voiceMessage)
                {
                    toBeVoiced = voice.SegmentText;
                    toBeVoiced = toBeVoiced.Replace("<p>", "");
                    toBeVoiced = toBeVoiced.Replace("</p>", "");
                    toBeVoiced = toBeVoiced.Replace("'", "");
                    toBeVoiced = toBeVoiced.Replace("'", "");
                    toBeVoiced = toBeVoiced.Replace("*", "");
                    toBeVoiced = toBeVoiced.Replace(" ", "~");
                    toBeVoiced = toBeVoiced.Replace("<br~/>", "");
                    toBeVoiced = toBeVoiced.Replace("~", " ");

                    VoiceMessage addVoiceMessage = new VoiceMessage();
                    addVoiceMessage.SegmentText = toBeVoiced;
                    addVoiceMessage.IdName = voice.IdName;
                    addVoiceMessage.SegmentName = voice.SegmentName;

                    patientRecords.AddVoicingMessage(addVoiceMessage);
                }
                return new JsonResult { Data = new { Success = true } };
            }
            catch(Exception er)
            {
                string s1 = er.Message;
                return new JsonResult { Data = new { Success = false } };
            }
        }
コード例 #12
0
ファイル: CreateWavFiles.cs プロジェクト: usbr/Pisces
        static void Main(string[] args)
        {
            if( args.Length != 1)
            {
                Console.WriteLine("Usage: CreateWavFiles.exe file.csv" );
                return;
            }

            var dir = Path.GetDirectoryName(args[0]);
            CsvFile csv = new CsvFile(args[0]);
            dir = Path.Combine(dir,"output");
            // Initialize a new instance of the SpeechSynthesizer.
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {
                Console.WriteLine("using voice :"+synth.Voice.Name);
                foreach (var item in synth.GetInstalledVoices())
                {
                   //.. Console.WriteLine(item.VoiceInfo.Name);
                }

                for (int i = 0; i < csv.Rows.Count; i++)
                {
                    // Set a value for the speaking rate. Slower to Faster (-10 to 10)
                    synth.Rate = -3;

                    // Configure the audio output.
                    string outputWavFileName = Path.Combine(dir, csv.Rows[i]["File Name"].ToString());
                    Console.WriteLine(outputWavFileName);
                    synth.SetOutputToWaveFile(outputWavFileName,
                      new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));

              // Create a SoundPlayer instance to play output audio file.
                    //System.Media.SoundPlayer m_SoundPlayer = new System.Media.SoundPlayer(outputWavFileName);

                    // Build a prompt.
                    PromptBuilder builder = new PromptBuilder();
                    builder.AppendText(csv.Rows[i]["Text"].ToString());

                    // Speak the prompt.
                    synth.Speak(builder);
                    //m_SoundPlayer.Play();
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
コード例 #13
0
        private static string FindFullVoiceName(string voiceArgument)
        {
            string voiceName = null;
            using (var synthesizer = new SpeechSynthesizer())
            {
                var installedVoices = synthesizer.GetInstalledVoices();
                var enabledVoices = installedVoices.Where(voice => voice.Enabled);

                var selectedVoice = enabledVoices.FirstOrDefault(voice => voice.VoiceInfo.Name.ToLowerInvariant().Contains(voiceArgument));
                if (selectedVoice != null)
                {
                    voiceName = selectedVoice.VoiceInfo.Name;
                }
            }
            return voiceName;
        }
コード例 #14
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            // Installed voices
            InstalledVoices = new List<string>();
            using (SpeechSynthesizer speaker = new SpeechSynthesizer()) {
                ReadOnlyCollection<InstalledVoice> voices = speaker.GetInstalledVoices();
                foreach (InstalledVoice voice in voices) {
                    InstalledVoices.Add(voice.VoiceInfo.Name);
                }
            }
        }
コード例 #15
0
ファイル: SpeechOut.cs プロジェクト: kingtut666/holly
 public string ListInstalledVoices()
 {
     SpeechSynthesizer voice = new SpeechSynthesizer();
     string ret = (" Installed Voices - Name, Culture, Age, Gender, Description, ID, Enabled\n");
     foreach (InstalledVoice vx in voice.GetInstalledVoices())
     {
         VoiceInfo vi = vx.VoiceInfo;
         ret += ("   " + vi.Name + ", " +
             vi.Culture + ", " +
             vi.Age + ", " +
             vi.Gender + ", " +
             vi.Description + ", " +
             vi.Id + ", " +
             vx.Enabled+"\n");
     }
     return ret;
 }
コード例 #16
0
        static void Main(string[] args)
        {
            string voiceFileName = args[0];
            string voiceFileNamemp3 = voiceFileName.Replace(".wav", ".mp3");
            string voiceFilePath = args[1];
            string toBeVoiced = args[2];
            int rate = int.Parse(args[3]); ;
            string voice = args[4];

            voiceFileName = voiceFileName.Replace("~", " ");
            voiceFilePath = voiceFilePath.Replace("~", " ");
            toBeVoiced = toBeVoiced.Replace("~", " ");
            voice = voice.Replace("~", " ");

            // Initialize a new instance of the SpeechSynthesizer.
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {

                //    // Output information about all of the installed voices. 
                //    Console.WriteLine("Installed voices -");
                foreach (InstalledVoice voice2 in synth.GetInstalledVoices())
                {
                    VoiceInfo info = voice2.VoiceInfo;
                    Console.WriteLine(" Voice Name: " + info.Name);
                }
            } 
            


            var reader = new SpeechSynthesizer();
            reader.Rate = rate;
            reader.SelectVoice(voice);

            try
            {
                reader.SetOutputToWaveFile(voiceFilePath + voiceFileName, new SpeechAudioFormatInfo(16025, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
                reader.Speak(toBeVoiced);
                reader.Dispose();
                WaveToMP3(voiceFilePath + voiceFileName, voiceFilePath + voiceFileNamemp3);
            }
            catch (Exception er)
            {
                string s1 = er.Message;
            }
        }
コード例 #17
0
    protected void Init() {
      synthesizer = new SpeechSynthesizer();
      synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);

      // List available voices
      foreach (InstalledVoice voice in synthesizer.GetInstalledVoices()) {
        VoiceInfo info = voice.VoiceInfo;
        Log("Name: " + info.Name + " Culture: " + info.Culture);
      }

      // Select voice from properties
      var v = ConfigManager.GetInstance().Find("voice.voice", "");
      if (!String.IsNullOrEmpty(v)) {
        synthesizer.SelectVoice(v);
        Log("Select voice: " + v);
      }
      Log("Voice: " + synthesizer.Voice.Name + " Rate: "+ synthesizer.Rate);
    }
コード例 #18
0
ファイル: WSRSpeaker.cs プロジェクト: Oniric75/WSRMacro
        // ==========================================
        //  WSRMacro CONSTRUCTOR
        // ==========================================
        protected WSRSpeaker()
        {
            // Build synthesizer
              synthesizer = new SpeechSynthesizer();
              synthesizer.SetOutputToDefaultAudioDevice();
              synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);

              foreach (InstalledVoice voice in synthesizer.GetInstalledVoices()) {
            VoiceInfo info = voice.VoiceInfo;
            WSRConfig.GetInstance().logInfo("TTS", "Name: " + info.Name + " Culture: " + info.Culture);
              }

              String v = WSRConfig.GetInstance().voice;
              if (v != null && v.Trim() != "") {
            WSRConfig.GetInstance().logInfo("TTS", "Select voice: " + v);
            synthesizer.SelectVoice(v);
              }
        }
コード例 #19
0
ファイル: SettingsUI.cs プロジェクト: TKubi/eve-intel-monitor
        public SettingsUI()
        {
            InitializeComponent();

            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {
                IList<InstalledVoice> voices = synth.GetInstalledVoices();
                foreach (InstalledVoice voice in voices)
                {
                    comboSelectedVoice.Items.Add(voice.VoiceInfo.Name);
                }

                if (synth.Voice != null)
                {
                    comboSelectedVoice.SelectedItem = synth.Voice.Name;
                }
            }
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: macumotob/TextReader
    static void TestVoices()
    {
      using ( SpeechSynthesizer synth = new SpeechSynthesizer())
      {

        // Output information about all of the installed voices. 
       
        foreach (InstalledVoice voice in synth.GetInstalledVoices())
        {
          VoiceInfo info = voice.VoiceInfo;
          string AudioFormats = "";
          foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
          {
            AudioFormats += String.Format("{0}\n",
            fmt.EncodingFormat.ToString());
          }

          Console.WriteLine(" Name:          " + info.Name);
          Console.WriteLine(" Culture:       " + info.Culture);
          Console.WriteLine(" Age:           " + info.Age);
          Console.WriteLine(" Gender:        " + info.Gender);
          Console.WriteLine(" Description:   " + info.Description);
          Console.WriteLine(" ID:            " + info.Id);
          Console.WriteLine(" Enabled:       " + voice.Enabled);
          if (info.SupportedAudioFormats.Count != 0)
          {
            Console.WriteLine(" Audio formats: " + AudioFormats);
          }
          else
          {
            Console.WriteLine(" No supported audio formats found");
          }

          string AdditionalInfo = "";
          foreach (string key in info.AdditionalInfo.Keys)
          {
            AdditionalInfo += String.Format("  {0}: {1}\n", key, info.AdditionalInfo[key]);
          }

          Console.WriteLine(" Additional Info - " + AdditionalInfo);
          Console.WriteLine();
        }
      }
    }
コード例 #21
0
        public Configure( SpeechSynthesizer setSpeechSynthesizer )
        {
            InitializeComponent();

            mSpeechSynthesizer = setSpeechSynthesizer;

            Rate.Value = mSpeechSynthesizer.Rate;
            Volume.Value = mSpeechSynthesizer.Volume;

            System.Collections.ObjectModel.ReadOnlyCollection<InstalledVoice> InstalledVoices = mSpeechSynthesizer.GetInstalledVoices();
            foreach( InstalledVoice InstalledVoice in InstalledVoices )
            {
                if (InstalledVoice.Enabled)
                {
                    VoiceList.Items.Add(InstalledVoice.VoiceInfo.Name);
                }
            }
            VoiceList.SelectedIndex = 0;
        }
コード例 #22
0
        static void Main(string[] args)
        {
            // Initialize a new instance of the SpeechSynthesizer.
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {

                // Output information about all of the installed voices.
                Console.WriteLine("Installed voices -");
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    VoiceInfo info = voice.VoiceInfo;
                    Console.WriteLine(" Voice Name: " + info.Name);
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
コード例 #23
0
        public override void Start(SpeechClient server)
        {
            base.Start(server);

            tts = new SpeechSynthesizer();
            bool voiceExists = false;
            foreach (InstalledVoice v in tts.GetInstalledVoices())
            {
                Console.WriteLine("WindowsTTS: Found '" + v.VoiceInfo.Name + "' voice.");
                if (v.VoiceInfo.Name == voice) voiceExists = true;
            }
            if (voiceExists) tts.SelectVoice(Properties.Settings.Default.Voice);
            tts.VisemeReached += new EventHandler<VisemeReachedEventArgs>(ProcessViseme);
            tts.PhonemeReached += new EventHandler<PhonemeReachedEventArgs>(ProcessPhonem);
            tts.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(Ended);
            tts.SpeakStarted += new EventHandler<SpeakStartedEventArgs>(Started);
            tts.BookmarkReached += new EventHandler<BookmarkReachedEventArgs>(Bookmark);
            tts.Rate = Properties.Settings.Default.SpeechRate;
            Console.WriteLine("Started WindowsTTS speech engine.");
        }
コード例 #24
0
ファイル: Form1.cs プロジェクト: cr88192/bgbtech_engine
        public Form1()
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();
            ReadOnlyCollection<InstalledVoice> voices;
            InstalledVoice vinf;
            string str;
            int i;

            InitializeComponent();

            str = "";
            voices = synth.GetInstalledVoices();
            for (i = 0; i < voices.Count; i++)
            {
                vinf = voices[i];
                str = vinf.VoiceInfo.Name;
                comboBox1.Items.Add(str);
            }

            //synth.SpeakAsync(str);
        }
コード例 #25
0
		public StoryTeller()
			: base()
		{
			_synthesizer = new SpeechSynthesizer();
			_voices = _synthesizer.GetInstalledVoices().ToList();

			if (_voices.Count <= 0)
			{ System.Diagnostics.Debug.WriteLine("MainWindow() No voices found!"); }
			else
			{
				_narratorVoice = _voices[0].VoiceInfo.Name;
				if (_voices.Count >= 2)
				{ _mentorVoice = _voices[1].VoiceInfo.Name; }
				else
				{ _mentorVoice = _voices[0].VoiceInfo.Name; }
			}

			_stories = new List<Story>();
			_currentlyPlaying = false;

			_synthesizer.SpeakCompleted += OnSpeakCompleted;
		}
コード例 #26
0
ファイル: WSRSpeaker.cs プロジェクト: Cactusbone/WSRMacro
        // ------------------------------------------
        //  CONSTRUCTOR
        // ------------------------------------------
        public WSRSpeaker(int device)
        {
            this.device = device;

              this.WaveOutSpeech = new WaveOut(WaveCallbackInfo.FunctionCallback());
              this.WaveOutSpeech.DeviceNumber = device;

              this.synthesizer = new SpeechSynthesizer();
              this.synthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);

              // Enumerate Voices
              foreach (InstalledVoice voice in synthesizer.GetInstalledVoices()) {
            VoiceInfo info = voice.VoiceInfo;
            WSRConfig.GetInstance().logInfo("TTS", "[" + device + "]" + "Name: " + info.Name + " Culture: " + info.Culture);
              }

              // Select Voice
              String v = WSRConfig.GetInstance().voice;
              if (v != null && v.Trim() != "") {
            WSRConfig.GetInstance().logInfo("TTS", "[" + device + "]" + "Select voice: " + v);
            synthesizer.SelectVoice(v);
              }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: vinsource/vincontrol
        private static void GenerateVideoFromPowerPoint(string sourcePath, string extension)
        {
            var pptApplication  = new Microsoft.Office.Interop.PowerPoint.Application();
            var pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoFalse);
            var slides          = pptPresentation.Slides;
            //CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutBlank];
            //Directory.GetCurrentDirectory() + @"/Untitled.jpg";

            var options = new List <string>();

            options.Add("Dark Stained Burr Walnut Veneer");
            options.Add("19\" 5-Spoke Chromed Alloy Sport Wheels");
            options.Add("Wood & Hide-Trimmed Steering Wheel");
            options.Add("Deep-Pile Carpet Mats W/Leather Trimming");
            options.Add("Valet Parking Key");
            options.Add("Universal Garage Door Opener");
            options.Add("Bluetooth Connection");

            var dirInfo     = new DirectoryInfo(sourcePath);
            var jpgFileList = new List <string>();

            if (dirInfo.Exists)
            {
                jpgFileList.AddRange(dirInfo.GetFiles().Where(f => f.Extension.Equals(extension)).OrderBy(f => f.LastWriteTime).Take(12).Select(fileToUpload => sourcePath + "\\" + fileToUpload.Name));
            }

            _Slide slide;

            for (int i = 0; i < jpgFileList.Count; i++)
            {
                slide = slides.Add(i + 1, PpSlideLayout.ppLayoutBlank);

                if (i.Equals(0))
                {
                    var shape = slide.Shapes.AddMediaObject2(@"C:\SCBBR53W26C036262\VINSoundLow.mp3", MsoTriState.msoFalse, MsoTriState.msoTrue, 50, 50, 20, 20);
                    //shape.AnimationSettings.SoundEffect.ImportFromFile(@"C:\SCBBR53W26C036262\ChillingMusic.wav");
                    shape.MediaFormat.Volume = 0.25f;
                    shape.AnimationSettings.PlaySettings.PlayOnEntry         = MsoTriState.msoTrue;
                    shape.AnimationSettings.PlaySettings.LoopUntilStopped    = MsoTriState.msoTrue;
                    shape.AnimationSettings.PlaySettings.HideWhileNotPlaying = MsoTriState.msoTrue;
                    shape.AnimationSettings.PlaySettings.StopAfterSlides     = jpgFileList.Count + 1;

                    var fileName = @"C:\SCBBR53W26C036262\2006 Bentley Continental Fly.wav";
                    using (var stream = File.Create(fileName))
                    {
                        var speechEngine = new SpeechSynthesizer {
                            Rate = -1, Volume = 100
                        };
                        speechEngine.SelectVoice(speechEngine.GetInstalledVoices()[0].VoiceInfo.Name);
                        speechEngine.SetOutputToWaveStream(stream);
                        var description = "Welcome to Newport Coast Auto. This's 2006 Bentley Continental Fly. ";
                        description += "Amazing highly rated value carfax certified car with previous Beverley Hills owner. Great options available on the cars. ";
                        description  = options.Aggregate(description, (current, option) => current + (option + ","));
                        description += ". Newport Coast Auto Invites You To Call 949-515-0800. With Any Questions Or To Schedule A Test Drive. The Entire Staff At Newport Coast Auto Are Dedicated And Experienced. We Always Strive To Provide A Level Of Service That Is Unsurpassed In Today's Busy And Automated World. Newport Coast Auto Offers Quality Pre-owned Vehicles At Competitive Prices. We Also Offer Extended Warranties, Financing, And Unmatched Customer Service. We Invite Trade-ins As Well";
                        speechEngine.Speak(description.Replace("***", ".").Replace("###", ".").Replace("*", "").Replace("#", ""));
                        stream.Flush();
                    }
                    var shapeSpeech = slide.Shapes.AddMediaObject2(fileName, MsoTriState.msoFalse, MsoTriState.msoTrue, 50, 50, 20, 20);
                    shapeSpeech.MediaFormat.Volume = 1;
                    shapeSpeech.AnimationSettings.PlaySettings.PlayOnEntry         = MsoTriState.msoTrue;
                    shapeSpeech.AnimationSettings.PlaySettings.LoopUntilStopped    = MsoTriState.msoTrue;
                    shapeSpeech.AnimationSettings.PlaySettings.HideWhileNotPlaying = MsoTriState.msoTrue;
                    shapeSpeech.AnimationSettings.PlaySettings.StopAfterSlides     = jpgFileList.Count + 1;

                    var pictureshape = slide.Shapes.AddPicture(jpgFileList[i], MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0);
                    //pictureshape.AnimationSettings.EntryEffect = PpEntryEffect.ppEffectDissolve;

                    var textshape = slide.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 50f, 140f, 400, 200);
                    textshape.Fill.Visible                       = MsoTriState.msoTrue;
                    textshape.Fill.ForeColor.RGB                 = Color.Black.ToArgb();
                    textshape.TextFrame.TextRange.Text           = "2006 Bentley Continental Fly";
                    textshape.TextFrame.TextRange.Font.Color.RGB = System.Drawing.Color.White.ToArgb();
                    textshape.TextFrame.TextRange.Font.Size      = 26;
                    textshape.AnimationSettings.EntryEffect      = PpEntryEffect.ppEffectFlyFromLeft;
                    textshape.AnimationSettings.TextLevelEffect  = PpTextLevelEffect.ppAnimateByFourthLevel;
                    textshape.AnimationSettings.TextUnitEffect   = PpTextUnitEffect.ppAnimateByWord;
                }
                else if (i.Equals(3))
                {
                    var pictureshape = slide.Shapes.AddPicture(jpgFileList[i], MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0);

                    slides.Range(i + 1).SlideShowTransition.EntryEffect = PpEntryEffect.ppEffectRevealBlackLeft;
                    //slides.Range(i + 1).SlideShowTransition.Duration = options.Count > 1 ? 1.5f * options.Count : 3;

                    var textshape = slide.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 50f, 20f, 450, 200);

                    textshape.Fill.Visible       = MsoTriState.msoTrue;
                    textshape.Fill.ForeColor.RGB = 0;
                    var textOptions = options.Aggregate("", (current, option) => current + ((char)9642 + " " + (option + "\r\n")));
                    textshape.TextFrame.TextRange.Text           = textOptions;
                    textshape.TextFrame.TextRange.Font.Color.RGB = System.Drawing.Color.White.ToArgb();
                    textshape.TextFrame.TextRange.Font.Size      = 22;
                    textshape.AnimationSettings.EntryEffect      = PpEntryEffect.ppEffectZoomCenter;
                    textshape.AnimationSettings.TextLevelEffect  = PpTextLevelEffect.ppAnimateByFourthLevel;
                    textshape.AnimationSettings.TextUnitEffect   = PpTextUnitEffect.ppAnimateByWord;
                }
                else
                {
                    var pictureshape = slide.Shapes.AddPicture(jpgFileList[i], MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0);
                    slides.Range(i + 1).SlideShowTransition.EntryEffect = PpEntryEffect.ppEffectRevealBlackLeft;
                }
            }

            slide = slides.Add(jpgFileList.Count + 1, PpSlideLayout.ppLayoutBlank);
            var logo = slide.Shapes.AddPicture(@"C:\SCBBR53W26C036262\logo.png", MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 140f);

            logo.AnimationSettings.EntryEffect = PpEntryEffect.ppEffectFlyFromLeft;

            var address = slide.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350f, 160f, 350, 200);

            address.Fill.Visible                       = MsoTriState.msoTrue;
            address.Fill.ForeColor.RGB                 = Color.WhiteSmoke.ToArgb();
            address.TextFrame.TextRange.Text           = "1719 Pomona Ave Costa Mesa, CA 92627";
            address.TextFrame.TextRange.Font.Color.RGB = Color.Gray.ToArgb();
            address.TextFrame.TextRange.Font.Size      = 26;
            address.AnimationSettings.EntryEffect      = PpEntryEffect.ppEffectFlyFromLeft;

            pptPresentation.SaveAs(@"C:\SCBBR53W26C036262\2006 Bentley Continental Fly.pptx");
        }
コード例 #28
0
        static void Main(string[] args)
        {

            bool isUnlocked = ftpclient.UnlockComponent("SCOTTGFTP_bsex2TmE3Znh");

            Database.PenChart = System.Configuration.ConfigurationManager.AppSettings["databaseConnection"];
            Database.ReminderConnection = System.Configuration.ConfigurationManager.AppSettings["reminderConnection"];
            Database.ReminderCloud = System.Configuration.ConfigurationManager.AppSettings["reminderCloud"];
            Database.ReminderOld = System.Configuration.ConfigurationManager.AppSettings["reminderOld"];
            Database.SRSMessage = System.Configuration.ConfigurationManager.AppSettings["srsMessage"];

            //patientRecords.EndOfDayUpdate();
            //UpDateProviderList();
            //if (System.Configuration
            //    .ConfigurationManager.AppSettings["createHistory"] == "T")
            //{
            //    CreateHistory();
            //}
            //reporting.PopulateReportTable();
            //monitorCommunications = new MonitorCommunications();
            //monitorCommunications.CreateSRSMessages(System.Configuration.ConfigurationManager.AppSettings["messagePath"],
            //    System.Configuration.ConfigurationManager.AppSettings["templatePath"],
            //    System.Configuration.ConfigurationManager.AppSettings["audioMessagingPath"]);

           // reporting.RepopulatePendingTelephone();
            //..patientRecords.BackupPendingTelephone

            timeToStopProgram = Convert.ToDateTime(System.Configuration
                .ConfigurationManager.AppSettings["timeToStopProgram"]);

            DeleteFolder(System.Configuration
                .ConfigurationManager.AppSettings["voiceFilePath"]);
            DeleteFolder(System.Configuration
                .ConfigurationManager.AppSettings["xmlPath"]);

            //For testing 
            //monitorCommunications = new MonitorCommunications();

            //monitorCommunications = new Monitoring.MonitorCommunications();
            //monitorCommunications.CreateSRSMessages();
            //reporting.PopulateReportTable();
            //Delete current records
            DeletePatientRecords();

            callingRecord = new List<CallingRecord>();
            appointments = new List<Appointments>();


            // Initialize a new instance of the SpeechSynthesizer.
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {

                //    // Output information about all of the installed voices. 
                //    Console.WriteLine("Installed voices -");
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    VoiceInfo info = voice.VoiceInfo;
                    Console.WriteLine(" Voice Name: " + info.Name);
                }
            } 
            
            CallingRecordsParameters callingRecordsParameters = Common.GetCallingRecordsParameters(System.Configuration.ConfigurationManager.AppSettings["callingRecordsParameters"]);

            //appointments = CallingRecordsFactory.GetRecords(callingRecordsParameters);
          //  PatientCommunication.
            PatientCommunication.Factory.CallingRecordsFactory.GetRecords(callingRecordsParameters);

            CheckTelephoneNumbers();
            CreateVoiceFiles();
            CreateXMLFiles();

            if (System.Configuration.ConfigurationManager.AppSettings["sendToRemoteSite"] == "T")
            {
                SendDocumentsViaFTP();
            }


            //UpDateProviderList();

            MakeCallParameters makeCallParameters = new Model.MakeCallParameters();

            makeCallParameters.AuthorizationID =
                System.Configuration.ConfigurationManager.AppSettings["authid"];
            makeCallParameters.AuthorizationToken =
                System.Configuration.ConfigurationManager.AppSettings["authtoken"];
            makeCallParameters.FromNumber =
                System.Configuration.ConfigurationManager.AppSettings["fromNumber"];

            makeCallParameters.AnswerURL =
                System.Configuration.ConfigurationManager.AppSettings["answerURL"];

            makeCallParameters.HangupURL =
                System.Configuration.ConfigurationManager.AppSettings["hangupURL"];

            makeCallParameters.AnswerMethod =
                System.Configuration.ConfigurationManager.AppSettings["answerMethod"];

            makeCallParameters.NameOfFirstFile =
                            System.Configuration.ConfigurationManager.AppSettings["nameOfFirstFile"];

            makeCallParameters.Type = "R";

            makeTelephoneCalls = new MakeTelephoneCalls(makeCallParameters);

            //Initial calls have been made
            //Start loop for rest of session
            int loop = 0;
            while (loop == 0)
            {
                monitorCommunications = new Monitoring.MonitorCommunications();
                monitorCommunications.GetCallingResults();
                //wait for 30 minutes
                //Thread.Sleep(1800000);
                Thread.Sleep(900000);

                monitorCommunications = new Monitoring.MonitorCommunications();
                monitorCommunications.GetCallingResults();

                makeCallParameters.Type = "M";
                
                makeTelephoneCalls = new MakeTelephoneCalls(makeCallParameters);

                DateTime rightNow = DateTime.Now;

                //check to see if there are calls left to be made
                if (patientRecords.NumberofRecordsToCall() == 0)
                {
                    PerformEndOfDayActivity();
                    loop = 1;
                }

                //Check to see if program should end
                if (rightNow.Ticks > timeToStopProgram.Ticks && loop != 1)
                {
                    PerformEndOfDayActivity();
                    loop = 1;
                }

                //check for time to see if application should be turned off
                //loop = 1;
            }
        }
コード例 #29
0
        public void TestDistortion()
        {
            EventWaitHandle waitHandle = new AutoResetEvent(false);

            using (MemoryStream stream = new MemoryStream())
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    Console.WriteLine(voice.VoiceInfo.Name);
                }

                synth.SetOutputToWaveStream(stream);
                synth.Speak("Anaconda golf foxtrot lima one niner six eight requesting docking.");
                stream.Seek(0, SeekOrigin.Begin);

                IWaveSource source = new WaveFileReader(stream);
                DmoDistortionEffect distortedSource = new DmoDistortionEffect(source);
                distortedSource.Edge = 10;
                distortedSource.PreLowpassCutoff = 4800;

                var soundOut = new WasapiOut();
                soundOut.Stopped += (s, e) => waitHandle.Set();

                soundOut.Initialize(distortedSource);
                soundOut.Play();

                waitHandle.WaitOne();

                soundOut.Dispose();
                distortedSource.Dispose();
                source.Dispose();
            }
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: Foxlider/TTS-Glitcher
        private static async Task Main(string[] args)
        {
            #region vars
            _r     = new Random();
            _synth = new SpeechSynthesizer();
            #endregion

            #region args parser
            if (args.Length < 3)
            {
                Console.WriteLine("No arguments sent. Please provide the arguments for the application to run\n");
                Console.WriteLine("- string     Path of the output .wav file\n");
                Console.WriteLine("- string     Language for the bot (en-US/fr-FR)\n");
                Console.WriteLine("- string[]   Text to say\n\nPress any key to exit...");
                Console.ReadKey();
                Environment.Exit(-1);
            }
            #endregion

            #region Voice init
            // Output information about all of the installed voices.
            _voices = _synth.GetInstalledVoices()
                      .Where(v =>
                             (v.VoiceInfo.Id == "MSTTS_V110_enUS_EvaM") ||
                             (v.VoiceInfo.Id == "MSTTS_V110_frFR_NathalieM"))
                      .Select(v => v.VoiceInfo)
                      .ToList();
            if (_voices == null || _voices.Count < 1)
            {
                Console.WriteLine("Voices were not recognized. Please install the required TTS voices to proceed.\nPress any key to exit...");
                Console.ReadKey();
                Environment.Exit(-2);
            }
            #endregion

            #region TTS stream creation
            var said = string.Join(" ", args.Skip(2));
            Console.WriteLine("Output text to file > " + args[0]);

            var stream = TtsToStream(said, args[1]);
            Console.WriteLine("Done.");
            #endregion

            #region Extract Stream's header
            stream.Seek(0, SeekOrigin.Begin);
            var ms = new MemoryStream();
            List <(string, byte[], object)> headerVals;
            headerVals = GetHeader(stream);                                              //Get all WAV File header values
            byte[] header = (byte[])GetValueFromHeader(headerVals, "fullHeader", false); //Extract the full header
            ms.Position     = header.Length;                                             // |Set the streams position
            stream.Position = header.Length;                                             // |

            var totalbytes      = stream.Length;
            int streamChunkSize = (int)GetValueFromHeader(headerVals, "chunkSize");
            int streamDataSize  = (int)GetValueFromHeader(headerVals, "dataChunkSize");
            var bitsPerSample   = (short)GetValueFromHeader(headerVals, "bitsPerSample");
            #endregion

            #region Glitching the stream
            MemoryStream msLQ = new MemoryStream();
            while (true) //Low Quality pass
            {
                var buffer    = new byte[BlockSize];
                var byteCount = await stream.ReadAsync(buffer, 0, BlockSize);

                if (byteCount == 0)
                {
                    break;
                }
                var  strm    = new MemoryStream();
                bool passing = true;
                for (int i = 0; i < buffer.Length; i += 2)
                {
                    if (passing)
                    {
                        strm.WriteByte(buffer[i]);
                        strm.WriteByte(buffer[i + 1]);
                        strm.WriteByte(buffer[i]);
                        strm.WriteByte(buffer[i + 1]);
                    }
                    passing = !passing;
                }
                await msLQ.WriteAsync(strm.ToArray(), 0, (int)strm.Length);
            }
            ms.Position   = header.Length;
            msLQ.Position = header.Length;
            while (true) //Copy stream to memorystream (to glitch it eventually)
            {
                var buffer    = new byte[BlockSize];
                var byteCount = await msLQ.ReadAsync(buffer, 0, BlockSize);

                if (byteCount == 0)
                {
                    break;
                }
                await Glitcher(ms, buffer, byteCount, bitsPerSample);

                //await ms.WriteAsync(buffer, 0, byteCount);
            }
            #endregion

            #region recreate Stream's header
            long newTotalBytes = ms.Length;
            int  newChunkSize  = (int)(newTotalBytes - (totalbytes - streamChunkSize));
            int  newDataSize   = (int)(newTotalBytes - (totalbytes - streamDataSize));

            List <(string, byte[], object)> newHeader = headerVals;
            headerVals[GetIndexFromHeader(headerVals, "chunkSize")]     = ("chunkSize", BitConverter.GetBytes(newChunkSize), newChunkSize);
            headerVals[GetIndexFromHeader(headerVals, "dataChunkSize")] = ("dataChunkSize", BitConverter.GetBytes(newDataSize), newDataSize);
            byte[] newBytes = SetHeader(newHeader).Item1;

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(newBytes, 0, newBytes.Length); //Rewrite the stream's header
            GetHeader(ms);
            #endregion

            #region Write stream to file
            ms.Seek(0, SeekOrigin.Begin);
            Console.WriteLine("Finished copying stream");
            FileStream fs = new FileStream(args[0], FileMode.OpenOrCreate); //Write memorystream to file
            ms.WriteTo(fs);
            #endregion

            #region Play down stream
            ms.Seek(0, SeekOrigin.Begin);
            var player = new SoundPlayer(ms); //Play the audio stream
            player.PlaySync();
            #endregion

            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
            Environment.Exit(0);
        }
コード例 #31
0
ファイル: Form1.cs プロジェクト: isidorefilmes/SAKLAS01
        public void LoadSpeech()
        {
            try
            {
                bot = new Bot();
                bot.isAcceptingUserInput = false;
                bot.loadSettings();
                user = new User("isidore", bot);
                bot.loadAIMLFromFiles();
                bot.isAcceptingUserInput = true;

                speaker = new SpeechSynthesizer(); // creating a instance

                // get the voices

                foreach (InstalledVoice voice in speaker.GetInstalledVoices())
                {
                    this.comboBox1.Items.Add(voice.VoiceInfo.Name);
                }

                engine = new SpeechRecognitionEngine();                                       // creating instance of a voice recognition

                engine.SetInputToDefaultAudioDevice();                                        // set the microphone

                engine.LoadGrammar(new DictationGrammar());                                   // ADD the dictation grammar

                engine.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(rec); // the recognition event

                engine.AudioLevelUpdated += new EventHandler <AudioLevelUpdatedEventArgs>(audioLevel);

                speaker.SpeakStarted   += new EventHandler <SpeakStartedEventArgs>(speaker_SpeakStarted);
                speaker.SpeakCompleted += new EventHandler <SpeakCompletedEventArgs>(speaker_SpeakCompleted);

                engine.RecognizeAsync(RecognizeMode.Multiple); // Starts recognition

                #region Loading key-value into the dictionary

                Commands = new Dictionary <string, string>();

                handler = new Handler(Commands);

                StreamReader reader = new StreamReader("cmds.txt");

                while (reader.Peek() >= 0)
                {
                    string line = reader.ReadLine();

                    var parts = line.Split('|');      // parts[0] key parts[1] value

                    Commands.Add(parts[0], parts[1]); // the commands into the Dicts
                }
                #endregion

                #region Create  the commands Grammar

                Grammar commandsGrammar = new Grammar(new GrammarBuilder(new Choices(Commands.Keys.ToArray())));
                commandsGrammar.Name = "cmds";
                engine.LoadGrammar(commandsGrammar);

                #endregion

                #region Load the open commands

                OpenCommands = new Dictionary <string, string>();
                StreamReader readerOpenCommands = new StreamReader("open.txt");
                while (readerOpenCommands.Peek() >= 0)
                {
                    string line  = readerOpenCommands.ReadLine();
                    var    parts = line.Split('|');

                    OpenCommands.Add(parts[0], parts[1]);
                }


                #endregion

                #region Create the open commands grammar

                Grammar opencommands = new Grammar(new GrammarBuilder(new Choices(OpenCommands.Keys.ToArray())));
                opencommands.Name = "open";

                engine.LoadGrammar(opencommands);

                #endregion

                #region Load sites into dic

                Sites = new Dictionary <string, string>();
                StreamReader readerSites = new StreamReader("sites.txt");

                while (readerSites.Peek() >= 0)
                {
                    string line  = readerSites.ReadLine();
                    var    parts = line.Split('|');
                    Sites.Add(parts[0], parts[1]);
                }

                Grammar sites = new Grammar(new GrammarBuilder(new Choices(Sites.Keys.ToArray())));
                sites.Name = "sites";

                engine.LoadGrammar(sites);

                #endregion

                #region Create the default command LIST

                DefaultCommands = new List <string>();

                DefaultCommands.Add("close");
                DefaultCommands.Add("minimize window");
                DefaultCommands.Add("maximize window");
                DefaultCommands.Add("show window");
                DefaultCommands.Add("show window");

                Grammar defaultCmds = new Grammar(new GrammarBuilder(new Choices(DefaultCommands.ToArray())));
                defaultCmds.Name = "defaultCmds";

                engine.LoadGrammar(defaultCmds);

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }
        }
コード例 #32
0
        static void Main(string[] args)
        {
            Console.WriteLine("Bienvenu dans Mathias");
            RUNNING = true;
            active  = true;
            GlobalManager.InitMathias();

            Console.WriteLine("Initialisation de la Kinect");
            speaker = new SpeechSynthesizer();

            List <InstalledVoice> voices = speaker.GetInstalledVoices().ToList();

            Console.WriteLine(speaker.Voice.Name);

            speaker.Speak("Démarrage en cours");
            kinectSensor = KinectSensor.GetDefault();
            if (kinectSensor != null)
            {
                Console.WriteLine("La kinect est récupérée");
                kinectSensor.Open();
                Console.WriteLine("La kinect est prête à recevoir les informations");

                Console.WriteLine("Récupération de l'audio beam");
                IReadOnlyList <AudioBeam> audioBeamList = kinectSensor.AudioSource.AudioBeams;
                Stream audioStream = audioBeamList[0].OpenInputStream();
                Console.WriteLine("Stream et audio beam OK");

                Console.WriteLine("Conversion de l'audioStream");
                convertStream = new KinectAudioStream(audioStream);
                Console.WriteLine("Conversion OK");
            }
            else
            {
                Console.WriteLine("Impossible de récupérer la kinect");
            }


            Console.WriteLine(GlobalManager.RI.Name + "Récupéré");

            if (GlobalManager.RI != null)
            {
                Console.WriteLine("Construction du grammar sample");
                speechEngine = new SpeechRecognitionEngine(GlobalManager.RI.Id);
                Console.WriteLine("Construction du grammar terminée");
                speechEngine.LoadGrammar((Grammar)GlobalManager.CONTEXT.GRAMMAR);
                speechEngine.SpeechRecognized          += SpeechRecognized;
                speechEngine.SpeechRecognitionRejected += SpeechRejected;

                convertStream.SpeechActive = true;

                speechEngine.SetInputToAudioStream(convertStream, new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
                speechEngine.RecognizeAsync(RecognizeMode.Multiple);
                Console.WriteLine("Il ne reste plus qu'a parler");
            }
            else
            {
                Console.WriteLine("Could not find speech recognizer");
            }

            while (GlobalManager.RUNNING)
            {
            }

            if (!GlobalManager.RUNNING)
            {
                speaker.Speak("Au revoir");
            }
        }
コード例 #33
0
        /*
         * Text to Speech
         */
        public Tts()
        {
            Console.WriteLine("TTS constructor called");



            //create sound player
            //player = new SoundPlayer();

            //create speech synthesizer
            tts = new SpeechSynthesizer();


            // show voices
            // Initialize a new instance of the SpeechSynthesizer.
            using (SpeechSynthesizer synth = new SpeechSynthesizer()) {
                // Output information about all of the installed voices.
                Console.WriteLine("Installed voices -");
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    VoiceInfo info         = voice.VoiceInfo;
                    string    AudioFormats = "";
                    foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
                    {
                        AudioFormats += String.Format("{0}\n",
                                                      fmt.EncodingFormat.ToString());
                    }

                    Console.WriteLine(" Name:          " + info.Name);
                    Console.WriteLine(" Culture:       " + info.Culture);
                    Console.WriteLine(" Age:           " + info.Age);
                    Console.WriteLine(" Gender:        " + info.Gender);
                    Console.WriteLine(" Description:   " + info.Description);
                    Console.WriteLine(" ID:            " + info.Id);
                    Console.WriteLine(" Enabled:       " + voice.Enabled);
                    if (info.SupportedAudioFormats.Count != 0)
                    {
                        Console.WriteLine(" Audio formats: " + AudioFormats);
                    }
                    else
                    {
                        Console.WriteLine(" No supported audio formats found");
                    }

                    string AdditionalInfo = "";
                    foreach (string key in info.AdditionalInfo.Keys)
                    {
                        AdditionalInfo += String.Format("  {0}: {1}\n", key, info.AdditionalInfo[key]);
                    }

                    Console.WriteLine(" Additional Info - " + AdditionalInfo);
                    Console.WriteLine();
                }
            }
            //Console.WriteLine("Press any key to exit...");
            //Console.ReadKey();



            //set voice
            tts.SelectVoiceByHints(VoiceGender.Male, VoiceAge.NotSet, 0, new System.Globalization.CultureInfo("pt-PT"));

            //tts.SelectVoice("...")


            //set function to play audio after synthesis is complete
            tts.SpeakCompleted += new EventHandler <SpeakCompletedEventArgs>(tts_SpeakCompleted);
        }
コード例 #34
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.splitContainer1.Dock  = DockStyle.Fill;
            this.splitContainer2.Dock  = DockStyle.Fill;
            this.lvMessages.Dock       = DockStyle.Fill;
            this.tbLog.Dock            = DockStyle.Fill;
            this.btnDisconnect.Enabled = false;

            //generic server
            _logger.Log("Initializing Client Module...");
            _server           = new CGenericServerWrapper();
            _server.NetworkID = 1;
            _server.Init("Voice.log");
            _logger.Log("Client Module initialized successfuly");

            //voice
            bool error = false;

            _logger.Log("Initializing Voice recognition Module...");
            recognizer  = new SpeechRecognitionEngine();
            synthesizer = new SpeechSynthesizer();

            System.Collections.ObjectModel.ReadOnlyCollection <InstalledVoice> voices = synthesizer.GetInstalledVoices();
            try
            {
                recognizer.SetInputToDefaultAudioDevice();
                recognizer.UnloadAllGrammars();
                recognizer.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
                SetVoice();
            }
            catch (ArgumentException ae)
            {
                error = true;
                _logger.Log(String.Format("Error in Voice recognition module initialization: {0}. ", ae.Message));
                MessageBox.Show(ae.Message);
            }
            catch (Exception ex)
            {
                error = true;
                _logger.Log(String.Format("Error in Voice recognition module initialization: {0}. ", ex.Message));
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (!error)
            {
                _logger.Log("Voice recognition Module initialized successfuly");
            }
        }
コード例 #35
0
        /*
         * Text to Speech constructor
         */
        public TTS()
        {
            Console.WriteLine("TTS constructor called");

            //create new speech synthesizer
            tts = new SpeechSynthesizer();

            //show voices
            //initialize a new instance of the SpeechSynthesizer
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {
                //output information for all installed voices
                Console.WriteLine("Installed voices -> ");
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    VoiceInfo voice_info   = voice.VoiceInfo;
                    string    AudioFormats = "";
                    foreach (SpeechAudioFormatInfo format in voice_info.SupportedAudioFormats)
                    {
                        AudioFormats += String.Format("{0}\n", format.EncodingFormat.ToString());
                        format.EncodingFormat.ToString();
                    }

                    //write voice information
                    Console.WriteLine("<--------- VOICE INFO --------->");
                    Console.WriteLine("Name: " + voice_info.Name);
                    Console.WriteLine("Culture: " + voice_info.Culture);
                    Console.WriteLine("Age: " + voice_info.Age);
                    Console.WriteLine("Gender: " + voice_info.Gender);
                    Console.WriteLine("Description: " + voice_info.Description);
                    Console.WriteLine("ID: " + voice_info.Id);
                    Console.WriteLine("Enabled: " + voice.Enabled);

                    //write voice audio formats
                    if (voice_info.SupportedAudioFormats.Count != 0)
                    {
                        Console.WriteLine("Audio Formats: " + AudioFormats);
                    }
                    else
                    {
                        Console.WriteLine("No Supported Audio Formats Found!");
                    }

                    //write additional information
                    string add_info = "";
                    foreach (string key in voice_info.AdditionalInfo.Keys)
                    {
                        add_info += String.Format("{0}:{1}\n", key, voice_info.AdditionalInfo[key]);
                    }
                    Console.WriteLine("Additional Information -> " + add_info);
                    Console.WriteLine();
                }
            }
            //quit
            //Console.WriteLine("Press any key to quit...");
            //Console.ReadKey();

            //set voice
            tts.SelectVoiceByHints(VoiceGender.Male, VoiceAge.NotSet, 0, new System.Globalization.CultureInfo("pt-PT"));

            //set voice function to play audio
            tts.SpeakCompleted += new EventHandler <SpeakCompletedEventArgs>(tts_SpeakCompleted);
        }
コード例 #36
0
        private void Load_Settings()
        {
            try
            {
                try
                {
                    gDebug = Convert.ToBoolean(OSAEObjectPropertyManager.GetObjectPropertyValue(gAppName, "Debug").Value);
                }
                catch
                {
                    Log.Error("I think the Debug property is missing from the Speech object type!");
                }
                Log.Info("Debug Mode Set to " + gDebug);
                gSelectedVoice = OSAEObjectPropertyManager.GetObjectPropertyValue(gAppName, "Voice").Value;
                bool   VoiceValid  = false;
                string aValidVoice = "";
                OSAEObjectPropertyManager.ObjectPropertyArrayDeleteAll(gAppName, "Voices");
                foreach (System.Speech.Synthesis.InstalledVoice i in oSpeech.GetInstalledVoices())
                {
                    if (aValidVoice == "")
                    {
                        aValidVoice = i.VoiceInfo.Name;
                    }
                    if (gSelectedVoice == "")
                    {
                        gSelectedVoice = i.VoiceInfo.Name;
                        OSAEObjectPropertyManager.ObjectPropertySet(gAppName, "Voice", gSelectedVoice, "SPEECH");
                        Log.Info("Default Voice Set to " + gSelectedVoice);
                    }
                    Log.Info("Adding Voice: " + i.VoiceInfo.Name);
                    if (gSelectedVoice == i.VoiceInfo.Name)
                    {
                        VoiceValid = true;
                    }
                    OSAEObjectPropertyManager.ObjectPropertyArrayAdd(gAppName, "Voices", i.VoiceInfo.Name, "Voice");
                }
                if (VoiceValid != true)
                {
                    gSelectedVoice = aValidVoice;
                }

                if (gSelectedVoice != "")
                {
                    oSpeech.SelectVoice(gSelectedVoice);
                    Log.Info("Current Voice Set to " + gSelectedVoice);
                }


                // Load the speech rate, which must be -10 to 10, and set it to 0 if it is not valid.
                Int16 iTTSRate = 0;
                try
                {
                    iTTSRate = Convert.ToInt16(OSAEObjectPropertyManager.GetObjectPropertyValue(gAppName, "TTS Rate").Value);
                }
                catch
                {
                    OSAEObjectPropertyManager.ObjectPropertySet(gAppName, "TTS Rate", iTTSRate.ToString(), gAppName);
                    Log.Info("TTS Rate was invalid! I changed it to " + iTTSRate.ToString());
                }
                if (iTTSRate < -10 || iTTSRate > 10)
                {
                    iTTSRate = 0;
                    OSAEObjectPropertyManager.ObjectPropertySet(gAppName, "TTS Rate", iTTSRate.ToString(), gAppName);
                    Log.Info("TTS Rate was invalid! I changed it to " + iTTSRate.ToString());
                }
                Log.Info("TTS Rate Set to " + iTTSRate.ToString());
                oSpeech.Rate = iTTSRate;
                Int16 iTTSVolume = 0;
                try
                {
                    iTTSVolume = Convert.ToInt16(OSAEObjectPropertyManager.GetObjectPropertyValue(gAppName, "TTS Volume").Value);
                }
                catch
                {
                    OSAEObjectPropertyManager.ObjectPropertySet(gAppName, "TTS Volume", iTTSVolume.ToString(), gAppName);
                    Log.Info("TTS Volume was invalid! I changed it to " + iTTSVolume.ToString());
                }
                if (iTTSVolume < -10 || iTTSVolume > 10)
                {
                    iTTSVolume = 0;
                    OSAEObjectPropertyManager.ObjectPropertySet(gAppName, "TTS Volume", iTTSVolume.ToString(), gAppName);
                    Log.Info("TTS Volume was invalid! I changed it to " + iTTSVolume.ToString());
                }
                oSpeech.Rate = iTTSVolume;
                Log.Info("TTS Volume Set to " + iTTSVolume.ToString());
            }
            catch (Exception ex)
            {
                Log.Error("Error in Load_Settings!", ex);
            }
        }
コード例 #37
0
ファイル: Program.cs プロジェクト: jaboc83/talktomegoose
        /// <summary>
        /// Main application logic
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // keep a running timer for phrase activation/inactivation
            runningTime.Start();

            // Read in the phrases
            using (TextFieldParser csvParser = new TextFieldParser("phrases.csv"))
            {
                csvParser.CommentTokens = new string[] { "#" };
                csvParser.SetDelimiters(new string[] { "," });
                csvParser.HasFieldsEnclosedInQuotes = true;

                // Skip the row with the column names
                csvParser.ReadLine();

                while (!csvParser.EndOfData)
                {
                    // Read current line fields, pointer moves to the next line.
                    string[] fields = csvParser.ReadFields();
                    phrases.Add(new Phrase
                    {
                        Message             = fields[0],
                        Weight              = int.Parse(fields[1]),
                        ActivateTimeInMin   = fields.Length > 2 && !string.IsNullOrWhiteSpace(fields[2]) ? int.Parse(fields[2]) : 0,
                        InactivateTimeInMin = fields.Length > 3 && !string.IsNullOrWhiteSpace(fields[3]) ? int.Parse(fields[3]) : (int?)null,
                        AudioFile           = fields.Length > 4 && !string.IsNullOrWhiteSpace(fields[4]) ? fields[4] : null
                    });
                }
            }

            // Read in config
            using (StreamReader r = new StreamReader("config.json"))
            {
                string json = r.ReadToEnd();
                cfg = JsonConvert.DeserializeObject <Configuration>(json);
            }

            // Setup voice
            Dictionary <string, int> countCheck  = new Dictionary <string, int>();
            SpeechSynthesizer        synthesizer = new SpeechSynthesizer
            {
                Volume = cfg.Volume,    // 0...100
                Rate   = cfg.SpeechRate // -10...10
            };

            // Chose the voice once here in case they don't want random voice option
            synthesizer.SelectVoice(synthesizer.GetInstalledVoices().OrderBy(x => Guid.NewGuid()).FirstOrDefault().VoiceInfo.Name);

            // Build the random phrase selector
            var selector = new DynamicRandomSelector <Phrase>();

            foreach (var phrase in phrases)
            {
                countCheck.Add(phrase.Message, 0);
                selector.Add(phrase, phrase.Weight);
            }
            selector.Build();

            bool   isValidSelection;
            Phrase selection = null;

            // Begin speaking
            while (true)
            {
                // Choose a random voice if needed
                if (cfg.RandomizeVoice)
                {
                    synthesizer.SelectVoice(synthesizer.GetInstalledVoices().OrderBy(x => Guid.NewGuid()).FirstOrDefault().VoiceInfo.Name);
                }
                isValidSelection = false;

                // Make sure the selected phrase is valid for the current game time
                while (!isValidSelection)
                {
                    selection = selector.SelectRandomItem();
                    if (runningTime.Elapsed.TotalMinutes > selection.ActivateTimeInMin &&
                        (selection.InactivateTimeInMin == null || runningTime.Elapsed.TotalMinutes < selection.InactivateTimeInMin))
                    {
                        isValidSelection = true;
                    }
                }

                // Print the phrase
                Console.WriteLine(selection);
                // Speak the phrase
                if (selection.AudioFile != null)
                {
                    using (var audioFile = new AudioFileReader(selection.AudioFile))
                        using (var outputDevice = new WaveOutEvent())
                        {
                            outputDevice.Init(audioFile);
                            outputDevice.Play();
                            while (outputDevice.PlaybackState == PlaybackState.Playing)
                            {
                                Thread.Sleep(500);
                            }
                        }
                }
                else
                {
                    synthesizer.Speak(selection.Message);
                }

                // Wait before speaking the next phrase
                Thread.Sleep(cfg.IntervalInSec * 1000);
            }
        }
コード例 #38
0
        public MainWindow()
        {
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {
                // Output information about all of the installed voices.
                Console.WriteLine("Installed voices -");
                foreach (InstalledVoice voice in synth.GetInstalledVoices())
                {
                    VoiceInfo info         = voice.VoiceInfo;
                    string    AudioFormats = "";
                    foreach (SpeechAudioFormatInfo fmt in info.SupportedAudioFormats)
                    {
                        AudioFormats += String.Format("{0}\n",
                                                      fmt.EncodingFormat.ToString());
                    }

                    Console.WriteLine(" Name:          " + info.Name);
                    Console.WriteLine(" Culture:       " + info.Culture);
                    Console.WriteLine(" Age:           " + info.Age);
                    Console.WriteLine(" Gender:        " + info.Gender);
                    Console.WriteLine(" Description:   " + info.Description);
                    Console.WriteLine(" ID:            " + info.Id);
                    Console.WriteLine(" Enabled:       " + voice.Enabled);
                    if (info.SupportedAudioFormats.Count != 0)
                    {
                        Console.WriteLine(" Audio formats: " + AudioFormats);
                    }
                    else
                    {
                        Console.WriteLine(" No supported audio formats found");
                    }

                    string AdditionalInfo = "";
                    foreach (string key in info.AdditionalInfo.Keys)
                    {
                        AdditionalInfo += String.Format("  {0}: {1}\n", key, info.AdditionalInfo[key]);
                    }

                    Console.WriteLine(" Additional Info - " + AdditionalInfo);
                    Console.WriteLine();
                }
            }

            InitializeComponent();

            string[] commands = File.ReadAllLines(@"commands.txt");
            foreach (string command in commands)
            {
                Console.WriteLine(command);
                //this.commandListItems.Add(command);
                this.commandList.Items.Add(command);
            }

            this.dispatcherTimer.Tick    += new EventHandler(dispatcherTimer_Tick);
            this.dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 1);
            this.dispatcherTimer.Start();

            this._recognizerChoices = new Choices(File.ReadAllLines(@"commands.txt"));
            this._recognizerBuilder = new GrammarBuilder(this._recognizerChoices);
            this._recognizerGrammar = new Grammar(this._recognizerBuilder);

            this._listenerChoices = new Choices(File.ReadAllLines(@"commands.txt"));
            this._listenerBuilder = new GrammarBuilder(this._listenerChoices);
            this._listenerGrammar = new Grammar(this._listenerBuilder);

            _recognizer.SetInputToDefaultAudioDevice();
            _recognizer.LoadGrammarAsync(this._recognizerGrammar);
            _recognizer.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(Default_SpeechRecognized);
            _recognizer.SpeechDetected   += new EventHandler <SpeechDetectedEventArgs>(_recognizer_SpeechRecognized);
            _recognizer.RecognizeAsync(RecognizeMode.Multiple);

            listener.SetInputToDefaultAudioDevice();
            listener.LoadGrammarAsync(this._listenerGrammar);
            listener.SpeechRecognized += new EventHandler <SpeechRecognizedEventArgs>(listener_SpeechRecognized);

            synthesizer.SetOutputToDefaultAudioDevice();

            synthesizer.SelectVoice("Microsoft Zira Desktop");

            foreach (ColumnDefinition col in this.mainGrid.ColumnDefinitions)
            {
                this.originalColumnSize.Add(col.Width);
            }

            this.notifyIcon                   = new NotifyIcon();
            this.notifyIcon.Icon              = Properties.Resources.icon; // new Icon(System.Windows.Application.GetResourceStream(this.baseIconUri).Stream);
            this.notifyIcon.MouseDoubleClick +=
                new System.Windows.Forms.MouseEventHandler
                    (NotifyIcon_MouseDoubleClick);

            // or this
            // synthesizer.SelectVoiceByHints(VoiceGender.Neutral, VoiceAge.NotSet, 0, CultureInfo.GetCultureInfo("en-us"));
        }
コード例 #39
0
        private void InitSpeechSynthesizer()
        {
            speechSynthesizer = new SpeechSynthesizer();
            speechSynthesizer.SetOutputToDefaultAudioDevice();

            speechSynthesizer.Rate = 1;
            speechSynthesizer.Volume = 100;

            var voiceList = speechSynthesizer.GetInstalledVoices();
            string voiceName = voiceList[0].VoiceInfo.Name;
            speechSynthesizer.SelectVoice(voiceName);
        }
コード例 #40
0
        private void LogIn_Load(object sender, EventArgs e)
        {
            string message = "Welcome!! Please Enter your Login Credentials";

            speechReader.Dispose();
            speechReader = new SpeechSynthesizer();
            IReadOnlyCollection <InstalledVoice> installedVoices = speechReader.GetInstalledVoices();
            InstalledVoice voice = installedVoices.First();

            speechReader.SelectVoice(voice.VoiceInfo.Name);
            speechReader.SpeakAsync(message);


            //Check if the Custom font Exits Then Use if it does exist
            if (File.Exists(@"Fonts\BOD_R.ttf"))
            {
                PrivateFontCollection pfc = new PrivateFontCollection();
                pfc.AddFontFile(@"Fonts\Blackletter686 BT.ttf");

                foreach (Control control in Controls)
                {
                    if (control is GroupBox)
                    {
                        (control).Font = new System.Drawing.Font(pfc.Families[0], 22.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    }
                }
            }
            //DataBase Access and Operations
            if (DBConnection.State.Equals(ConnectionState.Closed))
            {
                DBConnection.Open();
            }

            try
            {
                if (DBConnection.State.Equals(ConnectionState.Closed))
                {
                    DBConnection.Open();
                }
                sqlite_cmd             = DBConnection.CreateCommand();
                sqlite_cmd.CommandType = CommandType.Text;

                //Check if  First Table exists
                sqlite_cmd.CommandText = "SELECT name FROM sqlite_master WHERE name= 'AuthorizedUsers'";
                var name = sqlite_cmd.ExecuteScalar();
                //check if table exists
                if (name != null && name.ToString() == "AuthorizedUsers")
                {
                    return;
                }
                else
                {
                    //If not Exist then Create First Table
                    sqlite_cmd.CommandText = "CREATE TABLE AuthorizedUsers( id  INTEGER,UserName VARCHAR(45) PRIMARY KEY,Password VARCHAR(45));";
                    sqlite_cmd.ExecuteNonQuery();
                    //insert Defaults into First Table
                    sqlite_cmd.CommandText = "INSERT INTO AuthorizedUsers(id,UserName,Password) VALUES(1,'admin','1234');";
                    sqlite_cmd.ExecuteNonQuery();
                }

                //Check if  Second Table exists
                sqlite_cmd.CommandText = "SELECT name FROM sqlite_master WHERE name= 'AvailableSubjects'";
                var name2 = sqlite_cmd.ExecuteScalar();
                //check if table exists
                if (name2 != null && name.ToString() == "AvailableSubjects")
                {
                    return;
                }
                else
                {
                    //If not Exist then Create Second Table
                    sqlite_cmd.CommandText = "CREATE TABLE AvailableSubjects (id INTEGER PRIMARY KEY, Subjects VARCHAR(45), Teacher  VARCHAR(45));";
                    sqlite_cmd.ExecuteNonQuery();
                }

                //Check if  Third Table exists
                sqlite_cmd.CommandText = "SELECT name FROM sqlite_master WHERE name= 'Classes'";
                name = sqlite_cmd.ExecuteScalar();
                //check if table exists
                if (name != null && name.ToString() == "Classes")
                {
                    return;
                }
                else
                {
                    //If not Exist
                    //Create Third Table
                    sqlite_cmd.CommandText = "CREATE TABLE Classes (id INTEGER PRIMARY KEY,Class VARCHAR(45));";
                    sqlite_cmd.ExecuteNonQuery();

                    //insert Defaults into Third Table
                    sqlite_cmd.CommandText = "INSERT INTO Classes(id,Class)  VALUES(1,'Jss1')";
                    sqlite_cmd.ExecuteNonQuery();
                    sqlite_cmd.CommandText = "INSERT INTO Classes(id,Class)  VALUES(2,'Jss2')";
                    sqlite_cmd.ExecuteNonQuery();
                    sqlite_cmd.CommandText = "INSERT INTO Classes(id,Class)  VALUES(3,'Jss3')";
                    sqlite_cmd.ExecuteNonQuery();
                }

                //Check if  Fourth Table exists
                sqlite_cmd.CommandText = "SELECT name FROM sqlite_master WHERE name= 'StudentRecord'";
                name = sqlite_cmd.ExecuteScalar();
                //check if table exists
                if (name != null && name.ToString() == "StudentRecord")
                {
                    return;
                }
                else
                {
                    //If not Exist then Create First Table
                    //Create Fourth Table
                    sqlite_cmd.CommandText = @"CREATE TABLE StudentRecord (StudentID  STRING,FirstName VARCHAR(100),LastName VARCHAR(100),FullName  VARCHAR(100) PRIMARY KEY, DOB VARCHAR,
    State            VARCHAR(100),
    Sex              VARCHAR(10),
    Class            VARCHAR(10),
    English          INTEGER NOT NULL DEFAULT (0),
    Maths            INTEGER NOT NULL DEFAULT (0),
    BasicSci         INTEGER NOT NULL DEFAULT (0),
    BusStd           INTEGER NOT NULL DEFAULT (0),
    SocialStd        INTEGER NOT NULL DEFAULT (0),
    BasicTech        INTEGER NOT NULL DEFAULT (0),
    Total            INTEGER NOT NULL DEFAULT (0),
    Average          DOUBLE (20) NOT NULL DEFAULT (0),
    Address          VARCHAR (200),
    Image            BLOB,
    ParentPhone      VARCHAR (20),
    PrincipalComment VARCHAR,
    TeacherComment   VARCHAR
);";
                    sqlite_cmd.ExecuteNonQuery();
                }


                //Check if  Fifth Table exists
                sqlite_cmd.CommandText = "SELECT name FROM sqlite_master WHERE name= 'SessionDetails'";
                name = sqlite_cmd.ExecuteScalar();
                //check if table exists
                if (name != null && name.ToString() == "SessionDetails")
                {
                    return;
                }
                else
                {
                    //If not Exist then Create Fifth Table
                    sqlite_cmd.CommandText = "CREATE TABLE SessionDetails( id  INTEGER PRIMARY KEY,Term VARCHAR(45),Session VARCHAR(45),SchoolName VARCHAR(45), Address VARCHAR(45));";
                    sqlite_cmd.ExecuteNonQuery();
                    //insert Defaults into Fifth Table
                    sqlite_cmd.CommandText = @"INSERT INTO SessionDetails(Term,Session, SchoolName, Address) VALUES('1st', '2015/2016','YETKEM HIGH SCHOOL','Yetkem Avenue, Surulere, Alagbado, Lagos State.');";
                    sqlite_cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        } //End LogIn_Load
コード例 #41
0
 private void GetInstalledVoices()
 {
     _installedVoices = Speaker.GetInstalledVoices();
 }
コード例 #42
0
ファイル: Synthesizer.cs プロジェクト: NaolShow/Wolfy
 /// <summary>
 /// Returns all installed synthesizer voices
 /// </summary>
 public static ReadOnlyCollection <InstalledVoice> GetInstalledVoices()
 {
     return(SpeechSynthesizer.GetInstalledVoices());
 }
コード例 #43
0
        public MainWindow(bool fromVA = false)
        {
            InitializeComponent();

            this.fromVA = fromVA;

            // Start the EDDI instance
            EDDI.Instance.Start();

            // Configure the EDDI tab
            versionText.Text = Constants.EDDI_VERSION;

            //// Need to set up the correct information in the hero text depending on from where we were started
            if (fromVA)
            {
                heroText.Text = "Any changes made here will take effect automatically in VoiceAttack.  You can close this window when you have finished.";
            }
            else
            {
                heroText.Text = "If you are using VoiceAttack then please close this window before you start VoiceAttack for your changes to take effect.  You can access this window from VoiceAttack with the \"Configure EDDI\" command.";
            }

            EDDIConfiguration eddiConfiguration = EDDIConfiguration.FromFile();
            eddiHomeSystemText.Text = eddiConfiguration.HomeSystem;
            eddiHomeStationText.Text = eddiConfiguration.HomeStation;
            eddiInsuranceDecimal.Text = eddiConfiguration.Insurance.ToString(CultureInfo.InvariantCulture);
            eddiVerboseLogging.IsChecked = eddiConfiguration.Debug;

            Logging.Verbose = eddiConfiguration.Debug;

            // Configure the Companion App tab
            CompanionAppCredentials companionAppCredentials = CompanionAppCredentials.FromFile();
            companionAppEmailText.Text = companionAppCredentials.email;
            // See if the credentials work
            try
            {
                profile = CompanionAppService.Instance.Profile();
                if (profile == null)
                {
                    setUpCompanionAppComplete("Your connection to the companion app is good but experiencing temporary issues.  Your information should be available soon");
                }
                else
                {
                    setUpCompanionAppComplete("Your connection to the companion app is operational, Commander " + profile.Cmdr.name);
                }
            }
            catch (Exception)
            {
                if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_LOGIN)
                {
                    // Fall back to stage 1
                    setUpCompanionAppStage1();
                }
                else if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_CONFIRMATION)
                {
                    // Fall back to stage 2
                    setUpCompanionAppStage2();
                }
            }

            if (profile != null)
            {
                setShipyardFromConfiguration();
            }

            // Configure the Text-to-speech tab
            SpeechServiceConfiguration speechServiceConfiguration = SpeechServiceConfiguration.FromFile();
            List<string> speechOptions = new List<string>();
            speechOptions.Add("Windows TTS default");
            try
            {
                using (SpeechSynthesizer synth = new SpeechSynthesizer())
                {
                    foreach (InstalledVoice voice in synth.GetInstalledVoices())
                    {
                        if (voice.Enabled && (!voice.VoiceInfo.Name.Contains("Microsoft Server Speech Text to Speech Voice")))
                        {
                            speechOptions.Add(voice.VoiceInfo.Name);
                        }
                    }
                }

                ttsVoiceDropDown.ItemsSource = speechOptions;
                ttsVoiceDropDown.Text = speechServiceConfiguration.StandardVoice == null ? "Windows TTS default" : speechServiceConfiguration.StandardVoice;
            }
            catch (Exception e)
            {
                Logging.Warn("" + Thread.CurrentThread.ManagedThreadId + ": Caught exception " + e);
            }
            ttsVolumeSlider.Value = speechServiceConfiguration.Volume;
            ttsRateSlider.Value = speechServiceConfiguration.Rate;
            ttsEffectsLevelSlider.Value = speechServiceConfiguration.EffectsLevel;
            ttsDistortCheckbox.IsChecked = speechServiceConfiguration.DistortOnDamage;
            disableSsmlCheckbox.IsChecked = speechServiceConfiguration.DisableSsml;

            ttsTestShipDropDown.ItemsSource = ShipDefinitions.ShipModels;
            ttsTestShipDropDown.Text = "Adder";

            foreach (EDDIMonitor monitor in EDDI.Instance.monitors)
            {
                Logging.Debug("Adding configuration tab for " + monitor.MonitorName());

                PluginSkeleton skeleton = new PluginSkeleton(monitor.MonitorName());
                skeleton.plugindescription.Text = monitor.MonitorDescription();

                bool enabled;
                if (eddiConfiguration.Plugins.TryGetValue(monitor.MonitorName(), out enabled))
                {
                    skeleton.pluginenabled.IsChecked = enabled;
                }
                else
                {
                    // Default to enabled
                    skeleton.pluginenabled.IsChecked = true;
                    eddiConfiguration.ToFile();
                }

                // Add monitor-specific configuration items
                UserControl monitorConfiguration = monitor.ConfigurationTabItem();
                if (monitorConfiguration != null)
                {
                    monitorConfiguration.Margin = new Thickness(10);
                    skeleton.panel.Children.Add(monitorConfiguration);
                }

                TabItem item = new TabItem { Header = monitor.MonitorName() };
                item.Content = skeleton;
                tabControl.Items.Add(item);
            }

            foreach (EDDIResponder responder in EDDI.Instance.responders)
            {
                Logging.Debug("Adding configuration tab for " + responder.ResponderName());

                PluginSkeleton skeleton = new PluginSkeleton(responder.ResponderName());
                skeleton.plugindescription.Text = responder.ResponderDescription();

                bool enabled;
                if (eddiConfiguration.Plugins.TryGetValue(responder.ResponderName(), out enabled))
                {
                    skeleton.pluginenabled.IsChecked = enabled;
                }
                else
                {
                    // Default to enabled
                    skeleton.pluginenabled.IsChecked = true;
                    eddiConfiguration.ToFile();
                }

                // Add responder-specific configuration items
                UserControl monitorConfiguration = responder.ConfigurationTabItem();
                if (monitorConfiguration != null)
                {
                    monitorConfiguration.Margin = new Thickness(10);
                    skeleton.panel.Children.Add(monitorConfiguration);
                }

                TabItem item = new TabItem { Header = responder.ResponderName() };
                item.Content = skeleton;
                tabControl.Items.Add(item);
            }

            EDDI.Instance.Start();
        }
コード例 #44
0
 public override IEnumerable <IInstalledVoiceInfo> GetInstalledVoices()
 {
     AttachSynthesizer();
     return(_synthesizer.GetInstalledVoices().Select(installedVoice => new VoiceInfoWrapper_NetFramework(installedVoice.VoiceInfo, installedVoice.Enabled)));
 }
コード例 #45
0
        private void GeneratePowerPointFromImages(DealerViewModel dealer, CarShortViewModel car)
        {
            var pptApplication  = new Microsoft.Office.Interop.PowerPoint.Application();
            var pptPresentation = pptApplication.Presentations.Add(MsoTriState.msoFalse);
            var slides          = pptPresentation.Slides;
            //CustomLayout customLayout = pptPresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutBlank];

            var options = car.AdditonalOptions.Split(',').ToList();

            var sourcePath  = (ConfigurationHandler.DealerImages + "/" + dealer.DealerId + "/" + car.Vin + "/NormalSizeImages");
            var dirInfo     = new DirectoryInfo(sourcePath);
            var jpgFileList = new List <string>();

            if (dirInfo.Exists)
            {
                jpgFileList.AddRange(dirInfo.GetFiles().Where(f => f.Extension.Equals(".jpg")).OrderBy(f => f.LastWriteTime).Take(12).Select(fileToUpload => sourcePath + "\\" + fileToUpload.Name));
            }

            if (!jpgFileList.Any())
            {
                return;
            }

            _Slide slide;

            for (int i = 0; i < jpgFileList.Count; i++)
            {
                slide = slides.Add(i + 1, PpSlideLayout.ppLayoutBlank);

                if (i.Equals(0))
                {
                    var shape = slide.Shapes.AddMediaObject2(ConfigurationHandler.DealerImages + @"\VINSoundLow.wav", MsoTriState.msoFalse, MsoTriState.msoTrue, 50, 50, 20, 20);
                    shape.MediaFormat.Volume = 0.25f;
                    shape.AnimationSettings.PlaySettings.PlayOnEntry         = MsoTriState.msoTrue;
                    shape.AnimationSettings.PlaySettings.LoopUntilStopped    = MsoTriState.msoTrue;
                    shape.AnimationSettings.PlaySettings.HideWhileNotPlaying = MsoTriState.msoTrue;
                    shape.AnimationSettings.PlaySettings.StopAfterSlides     = jpgFileList.Count + 1;

                    var fileName = sourcePath + String.Format(@"\{0} {1} {2} {3}.wav", car.ModelYear, car.Make, car.Model, car.Trim);
                    using (var stream = File.Create(fileName))
                    {
                        var speechEngine = new SpeechSynthesizer {
                            Rate = -1, Volume = 100
                        };
                        speechEngine.SelectVoice(speechEngine.GetInstalledVoices()[0].VoiceInfo.Name);
                        speechEngine.SetOutputToWaveStream(stream);
                        var description = String.Format("Welcome to {0}. This's {1} {2} {3} {4}. ", dealer.Name, car.ModelYear, car.Make, car.Model, car.Trim);
                        description += "Amazing highly rated value carfax certified car. Great options available on the cars. ";
                        description  = options.Aggregate(description, (current, option) => current + (option + ","));
                        description += String.Format(". {0} Invites You To Call {1}. With Any Questions Or To Schedule A Test Drive. The Entire Staff At {0} Are Dedicated And Experienced. We Always Strive To Provide A Level Of Service That Is Unsurpassed In Today's Busy And Automated World. {0} Offers Quality Pre-owned Vehicles At Competitive Prices. We Also Offer Extended Warranties, Financing, And Unmatched Customer Service. We Invite Trade-ins As Well", dealer.Name, dealer.Phone);
                        speechEngine.Speak(description.Replace("***", ".").Replace("###", ".").Replace("*", "").Replace("#", ""));
                        stream.Flush();
                    }
                    var shapeSpeech = slide.Shapes.AddMediaObject2(fileName, MsoTriState.msoFalse, MsoTriState.msoTrue, 50, 50, 20, 20);
                    shapeSpeech.MediaFormat.Volume = 1;
                    shapeSpeech.AnimationSettings.PlaySettings.PlayOnEntry         = MsoTriState.msoTrue;
                    shapeSpeech.AnimationSettings.PlaySettings.LoopUntilStopped    = MsoTriState.msoTrue;
                    shapeSpeech.AnimationSettings.PlaySettings.HideWhileNotPlaying = MsoTriState.msoTrue;
                    shapeSpeech.AnimationSettings.PlaySettings.StopAfterSlides     = jpgFileList.Count + 1;

                    var pictureshape = slide.Shapes.AddPicture(jpgFileList[i], MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0);
                    //pictureshape.AnimationSettings.EntryEffect = PpEntryEffect.ppEffectDissolve;

                    var textshape = slide.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 50f, 140f, 400, 200);
                    textshape.Fill.Visible                       = MsoTriState.msoTrue;
                    textshape.Fill.ForeColor.RGB                 = Color.Black.ToArgb();
                    textshape.TextFrame.TextRange.Text           = String.Format("{0} {1} {2} {3}", car.ModelYear, car.Make, car.Model, car.Trim);
                    textshape.TextFrame.TextRange.Font.Color.RGB = System.Drawing.Color.White.ToArgb();
                    textshape.TextFrame.TextRange.Font.Size      = 26;
                    textshape.AnimationSettings.EntryEffect      = PpEntryEffect.ppEffectFlyFromLeft;
                    textshape.AnimationSettings.TextLevelEffect  = PpTextLevelEffect.ppAnimateByFourthLevel;
                    textshape.AnimationSettings.TextUnitEffect   = PpTextUnitEffect.ppAnimateByWord;
                }
                else if (i.Equals(2))
                {
                    var pictureshape = slide.Shapes.AddPicture(jpgFileList[i], MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0);

                    slides.Range(i + 1).SlideShowTransition.EntryEffect = PpEntryEffect.ppEffectRevealBlackLeft;
                    //slides.Range(i + 1).SlideShowTransition.Duration = options.Count > 1 ? 1.5f * options.Count : 3;

                    var textshape = slide.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 50f, 20f, 450, 200);

                    textshape.Fill.Visible       = MsoTriState.msoTrue;
                    textshape.Fill.ForeColor.RGB = 0;
                    var textOptions = options.Aggregate("", (current, option) => current + ((char)9642 + " " + (option + "\r\n")));
                    textshape.TextFrame.TextRange.Text           = textOptions;
                    textshape.TextFrame.TextRange.Font.Color.RGB = System.Drawing.Color.White.ToArgb();
                    textshape.TextFrame.TextRange.Font.Size      = 22;
                    textshape.AnimationSettings.EntryEffect      = PpEntryEffect.ppEffectZoomCenter;
                    textshape.AnimationSettings.TextLevelEffect  = PpTextLevelEffect.ppAnimateByFourthLevel;
                    textshape.AnimationSettings.TextUnitEffect   = PpTextUnitEffect.ppAnimateByWord;
                }
                else
                {
                    var pictureshape = slide.Shapes.AddPicture(jpgFileList[i], MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0);
                    slides.Range(i + 1).SlideShowTransition.EntryEffect = PpEntryEffect.ppEffectRevealBlackLeft;
                }
            }

            slide = slides.Add(jpgFileList.Count + 1, PpSlideLayout.ppLayoutBlank);
            if (!String.IsNullOrEmpty(dealer.Logo))
            {
                var logo = slide.Shapes.AddPicture(dealer.Logo, MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 140f);
                logo.AnimationSettings.EntryEffect = PpEntryEffect.ppEffectFlyFromLeft;
            }

            var address = slide.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationHorizontal, 350f, 160f, 350, 200);

            address.Fill.Visible                       = MsoTriState.msoTrue;
            address.Fill.ForeColor.RGB                 = Color.WhiteSmoke.ToArgb();
            address.TextFrame.TextRange.Text           = String.Format("{0} {1}, {2} {3}", dealer.Address, dealer.City, dealer.State, dealer.ZipCode);
            address.TextFrame.TextRange.Font.Color.RGB = Color.Gray.ToArgb();
            address.TextFrame.TextRange.Font.Size      = 26;
            address.AnimationSettings.EntryEffect      = PpEntryEffect.ppEffectFlyFromLeft;

            pptPresentation.SaveAs(sourcePath + String.Format(@"\{0} {1} {2} {3}.pptx", car.ModelYear, car.Make, car.Model, car.Trim));
        }
コード例 #46
0
        public MainWindow()
        {
            InitializeComponent();

            // Default to being primary
            Primary = true;

            // Start the EDDI instance
            EDDI.Instance.Start();

            // Configure the EDDI tab
            versionText.Text = Constants.EDDI_VERSION;

            EDDIConfiguration eddiConfiguration = EDDIConfiguration.FromFile();

            eddiHomeSystemText.Text      = eddiConfiguration.HomeSystem;
            eddiHomeStationText.Text     = eddiConfiguration.HomeStation;
            eddiInsuranceDecimal.Text    = eddiConfiguration.Insurance.ToString(CultureInfo.InvariantCulture);
            eddiVerboseLogging.IsChecked = eddiConfiguration.Debug;

            Logging.Verbose = eddiConfiguration.Debug;

            // Configure the Companion App tab
            CompanionAppCredentials companionAppCredentials = CompanionAppCredentials.FromFile();

            companionAppEmailText.Text = companionAppCredentials.email;
            // See if the credentials work
            try
            {
                profile = CompanionAppService.Instance.Profile();
                if (profile == null)
                {
                    setUpCompanionAppComplete("Your connection to the companion app is good but experiencing temporary issues.  Your information should be available soon");
                }
                else
                {
                    setUpCompanionAppComplete("Your connection to the companion app is operational, Commander " + profile.Cmdr.name);
                }
            }
            catch (Exception)
            {
                if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_LOGIN)
                {
                    // Fall back to stage 1
                    setUpCompanionAppStage1();
                }
                else if (CompanionAppService.Instance.CurrentState == CompanionAppService.State.NEEDS_CONFIRMATION)
                {
                    // Fall back to stage 2
                    setUpCompanionAppStage2();
                }
            }

            if (profile != null)
            {
                setShipyardFromConfiguration();
            }

            // Configure the Text-to-speech tab
            SpeechServiceConfiguration speechServiceConfiguration = SpeechServiceConfiguration.FromFile();
            List <string> speechOptions = new List <string>();

            speechOptions.Add("Windows TTS default");
            try
            {
                using (SpeechSynthesizer synth = new SpeechSynthesizer())
                {
                    foreach (InstalledVoice voice in synth.GetInstalledVoices())
                    {
                        if (voice.Enabled)
                        {
                            speechOptions.Add(voice.VoiceInfo.Name);
                        }
                    }
                }

                ttsVoiceDropDown.ItemsSource = speechOptions;
                ttsVoiceDropDown.Text        = speechServiceConfiguration.StandardVoice == null ? "Windows TTS default" : speechServiceConfiguration.StandardVoice;
            }
            catch (Exception e)
            {
                Logging.Warn("" + Thread.CurrentThread.ManagedThreadId + ": Caught exception " + e);
            }
            ttsVolumeSlider.Value        = speechServiceConfiguration.Volume;
            ttsRateSlider.Value          = speechServiceConfiguration.Rate;
            ttsEffectsLevelSlider.Value  = speechServiceConfiguration.EffectsLevel;
            ttsDistortCheckbox.IsChecked = speechServiceConfiguration.DistortOnDamage;

            ttsTestShipDropDown.ItemsSource = ShipDefinitions.ShipModels;
            ttsTestShipDropDown.Text        = "Adder";

            foreach (EDDIMonitor monitor in EDDI.Instance.monitors)
            {
                Logging.Debug("Adding configuration tab for " + monitor.MonitorName());

                PluginSkeleton skeleton = new PluginSkeleton(monitor.MonitorName());
                skeleton.plugindescription.Text = monitor.MonitorDescription();

                bool enabled;
                if (eddiConfiguration.Plugins.TryGetValue(monitor.MonitorName(), out enabled))
                {
                    skeleton.pluginenabled.IsChecked = enabled;
                }
                else
                {
                    // Default to enabled
                    skeleton.pluginenabled.IsChecked = true;
                    eddiConfiguration.ToFile();
                }

                // Add monitor-specific configuration items
                UserControl monitorConfiguration = monitor.ConfigurationTabItem();
                if (monitorConfiguration != null)
                {
                    monitorConfiguration.Margin = new Thickness(10);
                    skeleton.panel.Children.Add(monitorConfiguration);
                }

                TabItem item = new TabItem {
                    Header = monitor.MonitorName()
                };
                item.Content = skeleton;
                tabControl.Items.Add(item);
            }

            foreach (EDDIResponder responder in EDDI.Instance.responders)
            {
                Logging.Debug("Adding configuration tab for " + responder.ResponderName());

                PluginSkeleton skeleton = new PluginSkeleton(responder.ResponderName());
                skeleton.plugindescription.Text = responder.ResponderDescription();

                bool enabled;
                if (eddiConfiguration.Plugins.TryGetValue(responder.ResponderName(), out enabled))
                {
                    skeleton.pluginenabled.IsChecked = enabled;
                }
                else
                {
                    // Default to enabled
                    skeleton.pluginenabled.IsChecked = true;
                    eddiConfiguration.ToFile();
                }

                // Add responder-specific configuration items
                UserControl monitorConfiguration = responder.ConfigurationTabItem();
                if (monitorConfiguration != null)
                {
                    monitorConfiguration.Margin = new Thickness(10);
                    skeleton.panel.Children.Add(monitorConfiguration);
                }

                TabItem item = new TabItem {
                    Header = responder.ResponderName()
                };
                item.Content = skeleton;
                tabControl.Items.Add(item);
            }

            EDDI.Instance.Start();
        }
コード例 #47
0
        private void MenuItemOptions_OnClick(object sender, RoutedEventArgs e)
        {
            var optionsDialog = new Options(_synthesizer.GetInstalledVoices());

            optionsDialog.ShowDialog();
        }
コード例 #48
0
ファイル: applbot.cs プロジェクト: IrealiTY/ffxiv.act.applbot
        void initEncounterPlugin()
        {
            if (!InvokeRequired)
            {
                this.list_log.Columns.Add("Local Time", -1);
                this.list_log.Columns.Add("StopWatch", -2, HorizontalAlignment.Right);
                this.list_log.Columns.Add("Event", 200);
                this.list_log.Columns.Add("Details", -1);

                logFileName_active = getLatestFile(logFolder);
                log("Log File", false, logFileName_active);
                synthesizer.Volume = this.trackBar_volumeSlider.Value;  // 0...100

                //init server
                myTTTVServer = new tttvserver();

                //get installed voice
                foreach (InstalledVoice voice in synthesizer.GetInstalledVoices())
                {
                    VoiceInfo info = voice.VoiceInfo;
                    combo_voiceSelector.Items.Add(info.Name);
                }
                combo_voiceSelector.SelectedIndex = int.Parse(txt_voiceIndex.Text);
                //add ACT synch speak engine
                combo_voiceSelector.Items.Add("ACT synch mode (Not Reccomended)");

                //set fight timer
                fightTimer           = new System.Timers.Timer(1000); // Create a timer with a 1 second interval.
                fightTimer.Elapsed  += OnTimedEvent;                  // Hook up the Elapsed event for the timer.
                fightTimer.AutoReset = true;
                fightTimer.Enabled   = false;

                #region create joblist
                ffxiv_jobList      = new string[] { "whm", "ast", "sch", "war", "drk", "pld", "smn", "blm", "mch", "brd", "nin", "drg", "mnk" };
                ffxiv_jobSortOrder = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m" };
                ffxiv_classList    = new string[] { "heal", "heal", "heal", "tank", "tank", "tank", "caster", "caster", "range", "range", "melee", "melee", "melee" };
                ffxiv_jobSkillList.Add("#cure#, #cure ii#, #regen#, #stone iii#, #medica ii#");                                   //whm
                ffxiv_jobSkillList.Add("#helios#, #benefic ii#, #aspected benefic#, #combust ii#, #essential dignity#");          //ast
                ffxiv_jobSkillList.Add("#physick#, #adloquium#, #succor#, #lustrate#, #indomitability#, #broil#, #sacred soil#"); //sch
                ffxiv_jobSkillList.Add("#heavy swing#, #maim#, #skull Sunder#, #berserk#, #tomahawk#, #deliverance#");            //war
                ffxiv_jobSkillList.Add("#hard slash#, #unmend#, #plunge#");                                                       //drk
                ffxiv_jobSkillList.Add("#fast blade#, #shield lob#");                                                             //pld
                ffxiv_jobSkillList.Add("#fester#, #painflare#, #tri-disaster#, #deathflare#, #dreadwyrm trance#");                //smn
                ffxiv_jobSkillList.Add("#fire ii#, #fire iii#");                                                                  //blm
                ffxiv_jobSkillList.Add("#split shot#");                                                                           //mch
                ffxiv_jobSkillList.Add("#heavy shot#, #windbite#, #straight shot#, #venomous bite#");                             //brd
                ffxiv_jobSkillList.Add("#spinning edge#");                                                                        //nin
                ffxiv_jobSkillList.Add("#heavy thrust#, #true thrust#");                                                          //drg
                ffxiv_jobSkillList.Add("#bootshine#, #true strike#, #snap punch#, #twin snakes#");                                //mnk
                #endregion

                #region get xml files list
                string[] files = Directory.EnumerateFiles(pluginFolderName, "*.xml", SearchOption.AllDirectories).Select(Path.GetFileName).ToArray();//   System.IO.Directory.GetFiles("ffxiv.encounter\\xml");
                this.combo_xml_fightFile.Items.AddRange(files);
                #endregion

                #region Auto Update Stuff
                //log(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.Major.ToString());
                #endregion
            }
            else
            {
                Invoke(new Action(initEncounterPlugin));
            }
        }
コード例 #49
0
        private void startListen()
        {
            string request = "";

            while (true)
            {
                if (tcplistener.Server.Connected == false)
                {
                    tcplistener.Start();
                }
                TcpClient tcpclient = tcplistener.AcceptTcpClient();
                if (tcpclient.Connected == true)
                {
                    try
                    {
                        NetworkStream newworkstream = tcpclient.GetStream();
                        byte[]        buffer        = new byte[504];
                        int           readBytes     = newworkstream.Read(buffer, 0, 504);
                        request = Encoding.Default.GetString(buffer, 0, readBytes);//Encoding.ASCII.GetString(buffer).Substring(0, readBytes);
                        if (request.Length > 0)
                        {
                            //Byte[] sendBytes = Encoding.Default.GetBytes("SERVER_MSG");
                            //newworkstream.Write(sendBytes, 0, sendBytes.Length);
                            //SoundPlayer win = new SoundPlayer();
                            //win = new SoundPlayer(Properties.Resources.Phone);
                            //win.Play();

                            //listView3.Items.Clear();
                            ListViewItem item = new ListViewItem();
                            item.Name = "bz";
                            item.Text = DateTime.Now.ToShortTimeString() + ": " + request.ToString();
                            // listView3.Items.Add(item);
                            listView3.Items.Insert(0, item);
                            #region 以前的语音代码注释
                            // SpeechVoiceSpeakFlags spFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;

                            // SpVoice voice = new SpVoice();
                            //// voice.Voice = voice.GetVoices("Name=Microsoft Simplified Chinese", "").Item(0);
                            // voice.Rate = 0;
                            // voice.Volume = 100;

                            // voice.Speak(request.ToString(), spFlags);


                            #endregion

                            //Add By Zj 2012-08-07 新的语言叫号
                            ts_Caller.Icall _icall = ts_Caller.CallerFactory.NewCall(bjqxh);
                            _icall.Caller(request, _icall);
                            _icall.Call_hj();
                        }
                    }
                    catch (Exception ex)
                    {
                        SpeechSynthesizer syn = new SpeechSynthesizer();
                        System.Collections.ObjectModel.ReadOnlyCollection <System.Speech.Synthesis.InstalledVoice> rr = syn.GetInstalledVoices();
                        // syn.SelectVoice("VW Wang");

                        //  System.Globalization.CultureInfo cuinfo=new System.Globalization.CultureInfo(
                        syn.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Teen, 2);
                        // syn.Speak("F**k your Family");
                        syn.Speak(request.ToString());
                    }
                }



                else
                {
                    tcplistener.Server.Connect(IPAddress.Any, 8889);
                }
            }
        }
コード例 #50
0
        public SystemTextToSpeechEngine()
        {
            _synthesizer = new SpeechSynthesizer();

            _voices = _synthesizer.GetInstalledVoices().Select(v => new SystemVoice(v.VoiceInfo, this)).ToArray();
        }