예제 #1
1
        /* Constructor for page */
        public MainPage()
        {
            // Initialize the component model
            InitializeComponent();

            // Set the data context for the page bindings
            DataContext = App.ViewModel;

            // Create speech recognizer 
            _Recognizer = new SpeechRecognizerUI();

            // Bind up shake gesture
            ShakeGesturesHelper.Instance.ShakeGesture += new EventHandler<ShakeGestureEventArgs>(Instance_ShakeGesture);
            ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 4;
            ShakeGesturesHelper.Instance.Active = true;

            // Create demo recognizer and set grammer
            _DemoRecognizer = new SpeechRecognizerUI();
            _DemoRecognizer.Recognizer.Grammars.AddGrammarFromList("Demo", App.GrammerList);

            // Create speech synthesizer
            _Synthesizer = new SpeechSynthesizer();

            // Create signalr connection
            _Connection = new HubConnection("http://sagevoice.azurewebsites.net/");
            _Connection.StateChanged += change => ReportChange(change);

            // Create hub proxy
            _Hub = _Connection.CreateHubProxy("erpTicker");
            _Hub.On<string>("addResponse", data => OnResponse(data));
        }
예제 #2
1
        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);

        }
예제 #3
0
 private void btnStop_Click(object sender, EventArgs e)
 {
     synt.Pause();
     synt = new SpeechSynthesizer();
     play = false;
     textBox1.Text = string.Empty;
 }
예제 #4
0
 public Speaker()
 {
     if (null==msSpeech)
     {
         msSpeech = new SpeechSynthesizer();
     }
 }
예제 #5
0
파일: Form1.cs 프로젝트: Fackoz/Kalkylator
 private void buttonEquals_Click(object sender, EventArgs e)
 {
     switch (operationPerformed)
     {
         case "+":
             textBox_result.Text = (resultValue + Double.Parse(textBox_result.Text)).ToString();
             break;
         case "-":
             textBox_result.Text = (resultValue - Double.Parse(textBox_result.Text)).ToString();
             break;
         case "*":
             textBox_result.Text = (resultValue * Double.Parse(textBox_result.Text)).ToString();
             break;
         case "/":
             textBox_result.Text = (resultValue / Double.Parse(textBox_result.Text)).ToString();
             break;
         default:
             break;
     }
     resultValue = Double.Parse(textBox_result.Text);
     labelCurrentOperation.Text = "";
     SpeechSynthesizer speech = new SpeechSynthesizer();
     Button button = (Button)sender;
     speech.SpeakAsync(button.Text);
     speech.SpeakAsync(resultValue.ToString());
 }
예제 #6
0
파일: Program.cs 프로젝트: gnagypal/Anki
        private void GenerateTTS(Configuration cfg)
        {
            this.InitDestinationDirectory(cfg);

            using (var synthesizer = new SpeechSynthesizer())
            {
                this.InitializeSpeechSynthesizer(cfg, synthesizer);

                var xmlDoc = this.LoadXmlDocument(cfg);
                var rows = this.LoadRows(cfg, xmlDoc);

                foreach (var row in rows)
                {
                    string id = this.GetElementValue(cfg, row, cfg.IDElementName);
                    Console.WriteLine(id);

                    byte i = 0;
                    foreach (var textElementName in cfg.TextElementNames)
                    {
                        string textElement = this.GetElementValue(cfg, row, textElementName);
                        char postFix = (char)((byte)'A' + i);
                        string filename = cfg.Mp3FilePrefix + id + postFix + ".mp3";
                        string fullFilename = Path.Combine(cfg.DestinationDirectory, filename);
                        this.SpeakToMp3(cfg, synthesizer, fullFilename, textElement);
                        i++;
                    }
                }
            }
        }
예제 #7
0
파일: Sound.cs 프로젝트: prafullat/gminder
        static Sound()
        {
            voice = new SpeechSynthesizer();

            voice.Volume = 100;
            voice.Rate = 8 * voice.Rate / 3;
        }
예제 #8
0
        static void Main(string[] args)
        {
            SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
            speechSynthesizer.Speak("Welcome to the speaking performance monitor!");

            #region Performance Counters
            PerformanceCounter performanceCounter_CPU = new PerformanceCounter("Processor Information", "% Processor Time", "_Total");
            PerformanceCounter performanceCounter_RAM = new PerformanceCounter("Memory", "% Committed Bytes In Use");
            PerformanceCounter performanceCounter_TIME = new PerformanceCounter("System", "System Up Time"); 
            #endregion

            while (true)
            {
                float currentCPUPercentage = performanceCounter_CPU.NextValue();
                float currentRAMPercentage = performanceCounter_RAM.NextValue();

                Console.WriteLine("CPU Load:  {0}%", currentCPUPercentage);
                Console.WriteLine("RAM Usage: {0}%", currentRAMPercentage);

                string cpuLoadVocalMessage = String.Format("The current CPU load  is: {0}", currentCPUPercentage);
                string ramLoadVocalMessage = String.Format("The current RAM usage is: {0}", currentRAMPercentage);

                Thread.Sleep(500);
            }
        }
예제 #9
0
        private async void SpeakClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(inputTextBox.Text))
                MessageBox.Show("Introduce algun texto a leer.");
            else
            {
                try
                {
                    SpeechSynthesizer synth = new SpeechSynthesizer();

                    var voices = InstalledVoices.All.Where(v => v.Language == "es-ES").OrderByDescending(v => v.Gender);

                    VoiceGender gender = VoiceGender.Male;

                    if (rbMale.IsChecked == true)
                        gender = VoiceGender.Male;
                    else
                        gender = VoiceGender.Female;

                    synth.SetVoice(voices.Where(v => v.Gender == gender).FirstOrDefault());

                    await synth.SpeakTextAsync(inputTextBox.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
예제 #10
0
        public SpeechConversation(SpeechSynthesizer speechSynthesizer = null, SpeechRecognitionEngine speechRecognition = null)
        {
            SessionStorage = new SessionStorage();
            if(speechSynthesizer==null)
            {
                speechSynthesizer = new SpeechSynthesizer();
                speechSynthesizer.SetOutputToDefaultAudioDevice();
            }
            _speechSynthesizer = speechSynthesizer;
            if(speechRecognition==null)
            {
                speechRecognition = new SpeechRecognitionEngine(
                    new System.Globalization.CultureInfo("en-US")
                );
                // Create a default dictation grammar.
                DictationGrammar defaultDictationGrammar = new DictationGrammar();
                defaultDictationGrammar.Name = "default dictation";
                defaultDictationGrammar.Enabled = true;
                speechRecognition.LoadGrammar(defaultDictationGrammar);
                // Create the spelling dictation grammar.
                DictationGrammar spellingDictationGrammar = new DictationGrammar("grammar:dictation#spelling");
                spellingDictationGrammar.Name = "spelling dictation";
                spellingDictationGrammar.Enabled = true;
                speechRecognition.LoadGrammar(spellingDictationGrammar);

                // Configure input to the speech recognizer.
                speechRecognition.SetInputToDefaultAudioDevice();
            }
            _speechRecognition = speechRecognition;
        }
예제 #11
0
 public override async Task StartAsync()
 {
     _synth = new SpeechSynthesizer();
     await Log.ReportInfoFormatAsync(CancellationToken, "{0} started", Name);
     NotifyEntityChangeContext.ChangeNotifications<DeviceValue>.OnEntityUpdated += SpeechPlugin_OnEntityUpdated;
     _synth.SpeakAsync("Speech Started!");
 }
예제 #12
0
 public AudioService()
 {
     speechSynthesiser = new SpeechSynthesizer();
     BassNet.Registration(Settings.Default.BassRegistrationEmail, Settings.Default.BassRegistrationKey);
     Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);
     Application.Current.Exit += (sender, args) => Bass.BASS_Free();
 }
예제 #13
0
        public void VoiceCanBeHeard() {
            var synth = new SpeechSynthesizer();
            synth.SelectVoice("Microsoft Hazel Desktop");
            synth.Speak("This is an example of what to do");
            synth.Speak(NumberUtilities.Direction.Ascending.ToString());

        }
예제 #14
0
파일: Speaker.cs 프로젝트: TommyAGK/Flex
        public Speaker(Language lang = Language.English)
        {
            this.lang = lang;
            AsyncMode = false;  // Default to synchron speech
            UseSSML = false;	// Default to non-SSML speech

            try
            {
                // Create synthesizer
                ss = new SpeechSynthesizer();
                ss.SetOutputToDefaultAudioDevice();

                // Select language
                if (!UseSSML)
                {
                    switch (lang)
                    {
                        case Language.English: ss.SelectVoice("Microsoft Server Speech Text to Speech Voice (en-GB, Hazel)"); break;
                        case Language.Finish: ss.SelectVoice("Microsoft Server Speech Text to Speech Voice (fi-FI, Heidi)"); break;
                        case Language.Norwegian: ss.SelectVoice("Microsoft Server Speech Text to Speech Voice (nb-NO, Hulda)"); break;
                        case Language.Russian: ss.SelectVoice("Microsoft Server Speech Text to Speech Voice (ru-RU, Elena)"); break;
                        case Language.Swedish: ss.SelectVoice("Microsoft Server Speech Text to Speech Voice (sv-SE, Hedvig)"); break;
                        default: ss.SelectVoice("Microsoft Server Speech Text to Speech Voice (en-GB, Hazel)"); break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occured: '{0}'", e);
            }
        }
예제 #15
0
        private void handleDownloadStringComplete(object sender, DownloadStringCompletedEventArgs e)
        {
            if (Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable)
            {
                XNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/");
                titles = System.Xml.Linq.XElement.Parse(e.Result).Descendants("title")
                    .Where(m => m.Parent.Name == "item")
                    .Select(m => m.Value)
                    .ToArray();

                descriptions = XElement.Parse(e.Result).Descendants("description")
                    .Where(m => m.Parent.Name == "item")
                    .Select(m => m.Value)
                    .ToArray();

                images = XElement.Parse(e.Result).Descendants(media + "thumbnail")
                    .Where(m => m.Parent.Name == "item")
                    .Select(m => m.Attribute("url").Value)
                    .ToArray();

                SpeechSynthesizer synth = new SpeechSynthesizer();
                synth.SpeakTextAsync(titles[0]).Completed += new AsyncActionCompletedHandler(delegate(IAsyncAction action, AsyncStatus status)
                    {
                        synth.SpeakTextAsync(descriptions[0]);
                    });
                UpdatePrimaryTile(titles[0], images[0]);

            }
            else
            {
                MessageBox.Show("No network is available...");
            }
        }
예제 #16
0
파일: Notify.cs 프로젝트: foxjazz/IRCAL
 public Notify()
 {
     dc = DataClass.Instance;
     speaker = new SpeechSynthesizer();
     speaker.Rate = 1;
     speaker.Volume = 100;
 }
        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("~", " ");

            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;
            }
        }
예제 #18
0
 private void TestButton_Click(object sender, EventArgs e)
 {
     SpeechSynthesizer synth = new SpeechSynthesizer();
     synth.SelectVoice(_settings.CurrentTTSVoice.VoiceInfo.Name);
     synth.Rate = _settings.TTS_Rate;
     synth.SpeakAsync("This is " + _settings.CurrentTTSVoice.VoiceInfo.Description + " Speaking at a rate of " + _settings.TTS_Rate);
 }
예제 #19
0
        static public async Task StartTextToSpeech(string text)
        {
            if (!string.IsNullOrEmpty(text))
            {
                try
                {
                    if (_speech != null)
                    {
                        StopTextToSpeech();
                    }

                    var voice = GetSpeechVoice();
                    if (voice != null)
                    {
                        _speech = new SpeechSynthesizer();
                        _speech.Voice = voice;

                        SpeechSynthesisStream speechStream = await _speech.SynthesizeTextToStreamAsync(Utility.DecodeHtml(text));
                        _soundPlayer = new MediaElement();
                        _soundPlayer.SetSource(speechStream, speechStream.ContentType);
                        _soundPlayer.Play();
                    }
                }
                catch (Exception ex)
                {
                    AppLogs.WriteError("SpeechServices", ex);
                }
            }
        }
예제 #20
0
        /// <summary>
        /// have MediaElement defined in your XAML and pass it here
        /// </summary>
        /// <param name="_media"></param>
        public Speaker(MediaElement _media)
        {
            media = _media;
            media.MediaEnded += MediaElement_SpeakEnded;

            synthesizer = new SpeechSynthesizer();
        }
예제 #21
0
 public AerTalk()
 {
     rand = new Random();
     LastSpelledWord = "";
     _synth = new SpeechSynthesizer();
     _synth.SetOutputToDefaultAudioDevice();
 }
예제 #22
0
        /// <summary>
        /// 语音提示
        /// <summary>
        public void sayword(string strAlarm)
        {
            try
            {
                SpeechSynthesizer Talker = new SpeechSynthesizer();
                Talker.Rate = 2;//控制语速(-10--10)
                Talker.Volume = 100;//控制音量

                #region 获取本机上所安装的所有的Voice的名称
                //string voicestring = "";

                //foreach (InstalledVoice iv in Talker.GetInstalledVoices())
                //{
                //    voicestring += iv.VoiceInfo.Name + ",";
                //}
                //Microsoft Mary,Microsoft Mike,Microsoft Sam,Microsoft Simplified Chinese,SampleTTSVoice
                //Talker.SelectVoice("Microsoft Mary");
                #endregion

                //Talker.SetOutputToWaveFile("c:\soundfile.wav");//读取文件

                Talker.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Child, 2, System.Globalization.CultureInfo.CurrentCulture);
                Talker.SpeakAsync(strAlarm);
            }
            catch (Exception ex)
            {
                Log.WriteLog("语音提示控件" + ex.ToString());
            }
        }
예제 #23
0
파일: Speech.cs 프로젝트: Laubeee/ecnf
 public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
 {
     SpeechSynthesizer ss = new SpeechSynthesizer();
     ss.Speak(binder.Name);
     result = true;
     return true;
 }
        public void TestPhonemes()
        {
            EventWaitHandle waitHandle = new AutoResetEvent(false);

            using (MemoryStream stream = new MemoryStream())
            using (SpeechSynthesizer synth = new SpeechSynthesizer())
            {
                synth.SetOutputToWaveStream(stream);

                synth.SpeakSsml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"en-GB\"><s>This is your <phoneme alphabet=\"ipa\" ph=\"leɪkɒn\">Lakon</phoneme>.</s></speak>");

                //synth.SpeakSsml("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><speak version = \"1.0\" xmlns = \"http://www.w3.org/2001/10/synthesis\" xml:lang=\"en-GB\"><s>You are travelling to the <phoneme alphabet=\"ipa\" ph=\"ˈdɛltə\">delta</phoneme> system.</s></speak>");
                //synth.SpeakSsml("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><speak version = \"1.0\" xmlns = \"http://www.w3.org/2001/10/synthesis\" xml:lang=\"en-GB\"><s>You are travelling to the <phoneme alphabet=\"ipa\" ph=\"bliːiː\">Bleae</phoneme> <phoneme alphabet=\"ipa\" ph=\"θuːə\">Thua</phoneme> system.</s></speak>");
                //synth.SpeakSsml("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><speak version = \"1.0\" xmlns = \"http://www.w3.org/2001/10/synthesis\" xml:lang=\"en-GB\"><s>You are travelling to the Amnemoi system.</s></speak>");
                //synth.Speak("You are travelling to the Barnard's Star system.");
                stream.Seek(0, SeekOrigin.Begin);

                IWaveSource source = new WaveFileReader(stream);

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

                soundOut.Initialize(source);
                soundOut.Play();

                waitHandle.WaitOne();
                soundOut.Dispose();
                source.Dispose();
            }
        }
예제 #25
0
        /************ Helper Methods ************/
        // Helper Methods For Speech Synthesis Engine
        private void SetupSpeechSynthesizer()
        {
            // Start speech engine
            m_speechSynthesizer = new SpeechSynthesizer();

            // Do cute things with voice here
        }
예제 #26
0
        static void Main()
        {

            IList<string> args = new List<string>();
            string s = Console.ReadLine();
            while(!string.IsNullOrEmpty(s)){
                args.Add(s);
                s = Console.ReadLine();
            }

            foreach (string word in args)
            //Create wav file for each sound
            {
                using (FileStream f = new FileStream(word + ".wav", FileMode.Create))
                {
                    using (SpeechSynthesizer speak = new SpeechSynthesizer())
                    {
                        speak.SetOutputToWaveStream(f);
                        speak.Speak(word);
                    }
                }
                //Create phoneme text file for each word                
                using (FileStream f = new FileStream(word + ".txt", FileMode.Create))
                {
                    //call function to extract the phoneme
                    ExtractPhoneme2 extract = new ExtractPhoneme2();
                    string phoneme = extract.getPhoneme(word);

                    //Encode the phoneme and write  to file
                    Byte[] info = new UTF8Encoding(true).GetBytes(phoneme + "\n");                    
                    f.Write(info, 0, info.Length);
                }
            }
        }
예제 #27
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public GameplayScreen(Level lvl)
 {
     Narrator = new SpeechSynthesizer();
     TransitionOnTime = TimeSpan.FromSeconds(1.5);
     TransitionOffTime = TimeSpan.FromSeconds(0.5);
     mLevel = lvl;
 }
예제 #28
0
 MediaElement mediaElement = new MediaElement(); // Pamięć jest przydzielana tylko raz, dynamicznie
 async void speakString(string text)
 {
     var synth = new SpeechSynthesizer();
     SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);
     mediaElement.SetSource(stream, stream.ContentType);
     mediaElement.Play();
 }
예제 #29
0
        public MainForm()
        {
            InitializeComponent();
            message = new Dictionary<char, string>() {
                {'+',"increase screen opacity"},
                {'-',"decrease screen opacity"},
                {'1',"change color"},
                {'2',"change color"},
                {'3',"red light on"},
                {'4',"green light on"},
                {'5',"switch to night time"},
                {'6',"switch to day time"},
                {'7',"make snows"},
                {'8',"show rainbow"},
                {'9',"show bunny"},
                {'0',"make the bunny jump"}
            };

            synth = new SpeechSynthesizer();
            synth.SetOutputToDefaultAudioDevice();

            cars = new List<Car>();
            bunny = new Bunny(new Point(20, 20));
            rainbow = new Rainbow(new Point(0, 0));
            snow = new Snow(new Point(0, 0));
            traffic = new Traffic();

            sun = new Sun(new Point(Size.Width - 250, 10));
            moon = new Moon(new Point(Size.Width - 250, 10));

            carSound = new SoundPlayer(@"carSounds.wav");
            windSound = new SoundPlayer(@"Wind.wav");
            brake = new SoundPlayer(@"car-brake.wav");
        }
예제 #30
0
 public Speaker()
 {
     speaker = new SpeechSynthesizer();
 }
예제 #31
0
        public Conf()
        {
            AutoUpdate             = true;
            BlackList              = "";
            WhiteList              = "";
            BlockMode              = 0;
            GiftBlockMode          = 0;
            KeywordBlockMode       = 0;
            BlockUID               = true;
            DebugMode              = false;
            DownloadFailRetryCount = 5;
            DoNotKeepCache         = false;
            Engine               = 0;
            GiftBlackList        = "";
            GiftWhiteList        = "";
            KeywordBlackList     = "";
            KeywordWhiteList     = "";
            MinimumDanmakuLength = 0;
            MaximumDanmakuLength = 50;
            ReadInQueue          = true;
            ReadPossibility      = 100;
            TTSVolume            = 100;
            ReadSpeed            = 0;
            try
            {
                using (var synth = new SpeechSynthesizer())
                {
                    Vars.SystemSpeechAvailable = true;
                    var voice = synth.GetInstalledVoices().FirstOrDefault(x => x.Enabled);
                    if (voice == default)
                    {
                        VoiceName = "(无可用语音包)";
                    }
                    VoiceName = voice.VoiceInfo.Name;
                }
            }
            catch (Exception ex)
            {
                Vars.SystemSpeechAvailable   = false;
                Vars.SpeechUnavailableString = ex.ToString();
            }
            UseGoogleGlobal            = false;
            AllowDownloadMessage       = true;
            AllowConnectEvents         = true;
            ClearQueueAfterDisconnect  = true;
            CatchGlobalError           = true;
            SuperChatIgnoreRandomDitch = true;
            SaveCacheInTempDir         = true;
            SuppressLogOutput          = false;
            ClearCacheOnStartup        = true;
            OverrideToLogsTabOnStartup = false;
            AutoStartOnLoad            = false;
            SpeechPerson          = 0;
            EnableVoiceReply      = false;
            InstantVoiceReply     = false;
            MinifyJson            = true;
            SpeechPitch           = 0;
            GiftsThrottle         = true;
            GiftsThrottleDuration = 3;
            EnableUrlEncode       = true;
            VoiceReplyFirst       = false;
            IgnoreIfHitVoiceReply = false;
            DeviceGuid            = DefaultDeviceGuid;
            AutoFallback          = true;
            FullyAutomaticUpdate  = true;
            HttpAuth         = false;
            HttpAuthPassword = "";
            HttpAuthUsername = "";
            Headers          = new List <Header>();
            ReqType          = RequestType.JustGet;
            PostData         = "";

            CustomEngineURL = "https://tts.example.com/?text=$TTSTEXT";
            OnConnected     = "已成功连接至房间: $ROOM";
            OnDisconnected  = "已断开连接: $ERROR";
            OnDanmaku       = "$USER 说: $DM";
            OnGift          = "收到来自 $USER 的 $COUNT 个 $GIFT";
            OnLiveStart     = "直播已开始";
            OnLiveEnd       = "直播已结束";
            OnInteractEnter = "欢迎 $USER 进入直播间";
            OnInteractShare = "感谢 $USER 分享直播间";
            VoiceReplyRules = new List <VoiceReplyRule>();
        }
예제 #32
0
 private void Form1_Load(object sender, EventArgs e)
 {
     ss = new SpeechSynthesizer();
     // sRecognise.SpeechRecognized += sRecognise_SpeechRecognized;
 }
예제 #33
0
 public RaceStatusCommand(SpeechRecognitionEngine recognizer, SpeechSynthesizer synthesizer, Action recognized, DataCollector dataCollector)
     : base(recognizer, synthesizer, recognized)
 {
     this.dataCollector = dataCollector;
     SetGrammar("race status");
 }
예제 #34
0
        public override void ProcessCommand(byte[] parameter, IConnectionInfo connectionInfo)
        {
            switch ((UserInteractionCommunication)parameter[0])
            {
            case UserInteractionCommunication.TextToSpeech:
                var textToSpeechInfo =
                    new Serializer(typeof(TextToSpeechPackage)).Deserialize <TextToSpeechPackage>(parameter, 1);
                using (var speaker = new SpeechSynthesizer())
                {
                    speaker.Rate   = textToSpeechInfo.Speed;
                    speaker.Volume = textToSpeechInfo.Volume;
                    speaker.SelectVoice(textToSpeechInfo.VoiceName);
                    speaker.SetOutputToDefaultAudioDevice();
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)UserInteractionCommunication.SpeakingText });
                    speaker.Speak(textToSpeechInfo.Text);
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)UserInteractionCommunication.SpeakingFinished });
                }
                break;

            case UserInteractionCommunication.GetWelcomePackage:
                var package = new UserInteractionWelcomePackage();
                using (var speaker = new SpeechSynthesizer())
                    package.Voices =
                        speaker.GetInstalledVoices()
                        .Select(
                            x =>
                            new SpeechVoice
                    {
                        Culture     = x.VoiceInfo.Culture.TwoLetterISOLanguageName,
                        Name        = x.VoiceInfo.Name,
                        VoiceAge    = (SpeechAge)(int)x.VoiceInfo.Age,
                        VoiceGender = (SpeechGender)(int)x.VoiceInfo.Gender
                    })
                        .ToList();

                var data = new List <byte> {
                    (byte)UserInteractionCommunication.WelcomePackage
                };
                data.AddRange(new Serializer(typeof(UserInteractionWelcomePackage)).Serialize(package));
                connectionInfo.CommandResponse(this, data.ToArray());
                break;

            case UserInteractionCommunication.OpenInEditor:
                var textLength = BitConverter.ToInt32(parameter, 1);
                NotepadHelper.ShowMessage(Encoding.UTF8.GetString(parameter, 5, textLength),
                                          Encoding.UTF8.GetString(parameter, textLength + 5, parameter.Length - (5 + textLength)));
                connectionInfo.CommandResponse(this,
                                               new[] { (byte)UserInteractionCommunication.OpenedInEditorSuccessfully });
                break;

            case UserInteractionCommunication.NotifyIconMessage:
                var timeout     = BitConverter.ToInt32(parameter, 2);
                var titleLength = BitConverter.ToInt32(parameter, 6);
                var title       = Encoding.UTF8.GetString(parameter, 10, titleLength);
                var text        = Encoding.UTF8.GetString(parameter, 10 + titleLength,
                                                          parameter.Length - (10 + titleLength));

                using (var notifyIcon = new NotifyIcon {
                    Icon = SystemIcons.Application
                })
                {
                    notifyIcon.Visible = true;
                    notifyIcon.ShowBalloonTip(timeout, title, text, (ToolTipIcon)parameter[1]);
                    connectionInfo.CommandResponse(this,
                                                   new[] { (byte)UserInteractionCommunication.NotifyIconMessageOpened });
                    Thread.Sleep(timeout);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #35
0
 public Form1()
 {
     InitializeComponent();
     speech = new SpeechSynthesizer();
 }
예제 #36
0
        public void Init(AudioQueue qu, SpeechSynthesizer syn,
                         string title, string caption, Icon ic,
                         String text,             // if null, no text box or wait complete
                         bool waitcomplete, bool literal,
                         AudioQueue.Priority prio,
                         string startname, string endname,
                         string voicename,
                         string volume,
                         string rate,
                         Variables ef)        // effects can also contain other vars, it will ignore
        {
            comboBoxCustomPriority.Items.AddRange(Enum.GetNames(typeof(AudioQueue.Priority)));

            queue                  = qu;
            synth                  = syn;
            this.Text              = caption;
            Title.Text             = title;
            this.Icon              = ic;
            textBoxBorderTest.Text = "The quick brown fox jumped over the lazy dog";

            bool defaultmode = (text == null);

            if (defaultmode)
            {
                textBoxBorderText.Visible         = checkBoxCustomComplete.Visible = comboBoxCustomPriority.Visible = labelStartTrigger.Visible = labelEndTrigger.Visible =
                    checkBoxCustomLiteral.Visible = textBoxBorderStartTrigger.Visible = checkBoxCustomV.Visible = checkBoxCustomR.Visible = textBoxBorderEndTrigger.Visible = false;

                int offset = comboBoxCustomVoice.Top - textBoxBorderText.Top;
                foreach (Control c in panelOuter.Controls)
                {
                    if (!c.Name.Equals("Title"))
                    {
                        c.Location = new Point(c.Left, c.Top - offset);
                    }
                }

                this.Height -= offset;
            }
            else
            {
                textBoxBorderText.Text              = text;
                checkBoxCustomComplete.Checked      = waitcomplete;
                checkBoxCustomLiteral.Checked       = literal;
                comboBoxCustomPriority.SelectedItem = prio.ToString();
                textBoxBorderStartTrigger.Text      = startname;
                textBoxBorderEndTrigger.Text        = endname;
                buttonExtDevice.Visible             = false;
            }

            comboBoxCustomVoice.Items.Add("Default");
            comboBoxCustomVoice.Items.Add("Female");
            comboBoxCustomVoice.Items.Add("Male");
            comboBoxCustomVoice.Items.AddRange(synth.GetVoiceNames());
            if (comboBoxCustomVoice.Items.Contains(voicename))
            {
                comboBoxCustomVoice.SelectedItem = voicename;
            }
            else
            {
                comboBoxCustomVoice.SelectedIndex = 0;
            }

            int i;

            if (!defaultmode && volume.Equals("Default", StringComparison.InvariantCultureIgnoreCase))
            {
                checkBoxCustomV.Checked = false;
                trackBarVolume.Enabled  = false;
            }
            else
            {
                checkBoxCustomV.Checked = true;
                if (volume.InvariantParse(out i))
                {
                    trackBarVolume.Value = i;
                }
            }

            if (!defaultmode && rate.Equals("Default", StringComparison.InvariantCultureIgnoreCase))
            {
                checkBoxCustomR.Checked = false;
                trackBarRate.Enabled    = false;
            }
            else
            {
                checkBoxCustomR.Checked = true;
                if (rate.InvariantParse(out i))
                {
                    trackBarRate.Value = i;
                }
            }

            effects = ef;

            ExtendedControls.ThemeableFormsInstance.Instance?.ApplyToForm(this, System.Drawing.SystemFonts.DefaultFont);
        }
예제 #37
0
        // Speak using the MS speech synthesizer
        private void speak(MemoryStream stream, string voice, string speech)
        {
            var synthThread = new Thread(() =>
            {
                try
                {
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        if (voice != null && !voice.Contains("Microsoft Server Speech Text to Speech Voice"))
                        {
                            try
                            {
                                Logging.Debug("Selecting voice " + voice);
                                synth.SelectVoice(voice);
                                Logging.Debug("Selected voice " + synth.Voice.Name);
                            }
                            catch (Exception ex)
                            {
                                Logging.Warn("Failed to select voice " + voice, ex);
                            }
                        }
                        Logging.Debug("Post-selection");

                        Logging.Debug("Configuration is " + configuration == null ? "<null>" : JsonConvert.SerializeObject(configuration));
                        synth.Rate   = configuration.Rate;
                        synth.Volume = configuration.Volume;

                        synth.SetOutputToWaveStream(stream);

                        if (speech.Contains("<"))
                        {
                            Logging.Debug("Obtaining best guess culture");
                            string culture = bestGuessCulture(synth);
                            Logging.Debug("Best guess culture is " + culture);
                            //speech = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"" + bestGuessCulture(synth) + "\" onlangfailure=\"ignorelang\"><s>" + speech + "</s></speak>";
                            speech = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"" + bestGuessCulture(synth) + "\"><s>" + speech + "</s></speak>";
                            Logging.Debug("Feeding SSML to synthesizer: " + speech);
                            synth.SpeakSsml(speech);
                        }
                        else
                        {
                            Logging.Debug("Feeding normal text to synthesizer: " + speech);
                            synth.Speak(speech);
                        }
                        stream.ToArray();
                    }
                }
                catch (ThreadAbortException)
                {
                    Logging.Debug("Thread aborted");
                }
                catch (Exception ex)
                {
                    Logging.Warn("speech failed: ", ex);
                }
            });

            synthThread.Start();
            synthThread.Join();
            stream.Position = 0;
        }
예제 #38
0
        private void spe_Click(object sender, EventArgs e)
        {
            SpeechSynthesizer ss = new SpeechSynthesizer();

            ss.Speak(label5.Text);
        }
예제 #39
0
        private void button1_Click(object sender, EventArgs e)
        {
            SpeechSynthesizer ss     = new SpeechSynthesizer();
            string            answer = textBox1.Text;
            bool H = true;

            if (answer == "")
            {
                note.ForeColor = System.Drawing.Color.Red;
                note.Text      = " Please! Write your answer ";
            }
            else
            {
                if (H == true)
                {
                    string ans   = label5.Text;
                    string ysub  = textBox1.Text;
                    string ans1  = "";
                    string ysub1 = "";
                    string T;
                    int    t;
                    string F;
                    int    f;
                    ans  = ans.ToLower();
                    ysub = ysub.ToLower();
                    for (int i = 0; i < ans.Length; i++)
                    {
                        if (ans[i] != ' ')
                        {
                            ans1 = ans1 + ans[i];
                        }
                    }
                    for (int i = 0; i < ysub.Length; i++)
                    {
                        if (ysub[i] != ' ')
                        {
                            ysub1 = ysub1 + ysub[i];
                        }
                    }
                    if (ans1 == ysub1)
                    {
                        note.ForeColor = System.Drawing.Color.Green;
                        note.Text      = "Right!";
                        T          = right.Text;
                        t          = Convert.ToInt32(T);
                        t          = t + 1;
                        T          = Convert.ToString(t);
                        right.Text = T;
                        True.Text  = T;
                        ss.Speak(answer);
                        note.Text = "";
                        Console.OutputEncoding = Encoding.Unicode;
                        string   filePath = @"Data.txt";
                        string   filetest = @"test.txt";
                        int      range    = 0; //number of word
                        int      id;           // id random of word
                        string[] lines;
                        string[] testtxt;
                        string[] nm;
                        string   QA       = "";// Question and answer
                        string   Ques     = "";
                        string   Ans      = "";
                        string   Id       = "";
                        int      j        = 0;
                        int      k        = 0;
                        string   spee     = "";
                        Boolean  check    = false;
                        Boolean  check1   = true;
                        Random   idrandom = new Random();

                        textBox1.Text = "";                  //clear ans
                        if (System.IO.File.Exists(filePath)) // Process number of word
                        {
                            lines = System.IO.File.ReadAllLines(filePath);
                            range = lines.Length;
                            if (range == 2)
                            {
                                H = false;
                            }
                            //////////////////////////////////////////

                            /*String filepath1 = "testtg.txt";// đường dẫn của file muốn tạo
                             * FileStream fs1 = new FileStream(filepath1, FileMode.Append);//Tạo file mới tên là test.txt
                             * StreamWriter sWriter1 = new StreamWriter(fs1, Encoding.UTF8);//fs là 1 FileStream
                             * for (int i = 0; i < range; i++)
                             * {
                             *  if (i == Convert.ToInt64(label4.Text))
                             *      {
                             *      sWriter1.WriteLine(lines[Convert.ToInt64(label4.Text)] + "*");
                             *  }
                             *  else
                             *  {
                             *      sWriter1.WriteLine(lines[i]);
                             *  }
                             *
                             * }
                             *
                             * sWriter1.Flush();
                             * fs1.Close();
                             * File.Delete("data.txt");
                             * File.Move("testtg.txt", "data.txt");*/
                            //////////////////////////////////////////
                            String       filepath2 = "testtg2.txt";                              // đường dẫn của file muốn tạo
                            FileStream   fs2       = new FileStream(filepath2, FileMode.Append); //Tạo file mới tên là test.txt
                            StreamWriter sWriter2  = new StreamWriter(fs2, Encoding.UTF8);       //fs là 1 FileStream
                            for (int i = 0; i < range - 1; i++)
                            {
                                if (i != Convert.ToInt64(label4.Text))
                                {
                                    sWriter2.WriteLine(lines[i]);
                                }
                            }
                            range = range - 1;
                            sWriter2.Flush();
                            fs2.Close();
                            File.Delete("data.txt");
                            File.Move("testtg2.txt", "data.txt");
                        }/////////////
                        id = idrandom.Next(1, range);
                        if (System.IO.File.Exists(filePath))// Process number of word
                        {
                            lines = System.IO.File.ReadAllLines(filePath);
                            QA    = lines[id];
                        }
                        for (int i = 0; i < QA.Length; i++)// get Id
                        {
                            if (QA[i] == '.')
                            {
                                check1 = false;
                                j      = i;
                                break;
                            }
                            if (check1 == true)
                            {
                                Id = Id + QA[i];
                            }
                        }
                        for (int i = j + 1; i < QA.Length; i++)//Get question and answer
                        {
                            if (QA[i] == '/')
                            {
                                k = i;
                                break;
                            }
                            else
                            {
                                if (QA[i] == '-')
                                {
                                    check = true;
                                }
                                if (check1 == false)
                                {
                                    if (check == false)
                                    {
                                        Ques = Ques + QA[i];
                                    }
                                    else
                                    {
                                        if (QA[i] != '-')
                                        {
                                            Ans = Ans + QA[i];
                                        }
                                    }
                                }
                            }
                        }
                        for (int i = k + 1; i < QA.Length; i++)
                        {
                            spee = spee + QA[i];
                        }
                        label4.Text       = Id;
                        TextQuestion.Text = Ques;
                        label5.Text       = Ans;
                        speech.Text       = spee;
                    }
                    else
                    {
                        note.ForeColor = System.Drawing.Color.Red;
                        note.Text      = "Wrong!";
                        F          = wrong.Text;
                        f          = Convert.ToInt32(F);
                        f          = f + 1;
                        F          = Convert.ToString(f);
                        wrong.Text = F;
                        False.Text = F;
                    }
                }
                else
                {
                    MessageBox.Show("Completed!!!");
                }
            }
        }
예제 #40
0
        private static void speak()
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();

            synth.Speak("Hello! This is the GradBook program");
        }
예제 #41
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);
        }
예제 #42
0
        private void HelloForm_Shown(object sender, EventArgs e)
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();

            synth.SetOutputToDefaultAudioDevice();
            synth.Speak("Приветствую!");
            DateTime now = DateTime.Now;

            time = now.ToString("HH:MM");
            string bufHour = "";

            bufHour += time[0];
            bufHour += time[1];
            string morning = "4";
            string day     = "12";
            string evening = "18";
            string night   = "24";

            if (Convert.ToInt32(bufHour) > Convert.ToInt32(evening) && Convert.ToInt32(bufHour) < Convert.ToInt32(night) || Convert.ToInt32(bufHour) == Convert.ToInt32(evening))
            {
                int choice = r.Next(1, 7);
                switch (choice)
                {
                case 1:
                    label1.Text = "Вечер - это время";
                    label2.Text = "в кругу родных";
                    label3.Text = "сериалов, пледа и депрессии...";
                    break;

                case 2:
                    label1.Text = "О, чудесное время, когда ";
                    label2.Text = "можно расслабиться и сделать работу,";
                    label3.Text = "которую не успели закончить днем.";
                    break;

                case 3:
                    label1.Text = "Эй, Брэйн, чем мы будем заниматься ";
                    label2.Text = "Тем жсегодня вечером?Тем же, чем и всегда,";
                    label3.Text = "Пинки, попробуем завоевать мир.";
                    break;

                case 4:
                    label1.Text = "Если тебе никто не позвонил вечером,";
                    label2.Text = "всегда можно включить";
                    label3.Text = "любимого бота и нажаловаться.";
                    break;

                case 5:
                    label1.Text = "Сегодня вечером я жду";
                    label2.Text = "чего - то доброго, светлого,";
                    label3.Text = "нефильтрованного.";
                    break;

                case 6:
                    label1.Text = "Настоящее мужество — ";
                    label2.Text = "залезть после шести вечера в холодильник за кефиром";
                    label3.Text = "и взять не вино и кальмара, а КЕФИР!";
                    break;
                }
                label1.Visible = true;
                label2.Visible = true;
                label3.Visible = true;
                string say = label1.Text + " " + label2.Text + " " + label3.Text;
                synth.Speak(say);
            }

            if (Convert.ToInt32(bufHour) > Convert.ToInt32(morning) && Convert.ToInt32(bufHour) < Convert.ToInt32(day) || Convert.ToInt32(bufHour) == Convert.ToInt32(morning))
            {
                int  choice = r.Next(1, 7);
                bool trig   = false;
                switch (choice)
                {
                case 1:
                    label1.Text = "Какое ужасное утро!";
                    label2.Text = "Зато вы сегодня сияете";
                    label3.Text = "непревзойденной красотой!";
                    break;

                case 2:
                    label1.Text = "Вставайте, господин!";
                    label2.Text = "Вас ждут великие свершения!";
                    trig        = true;
                    break;

                case 3:
                    label1.Text = "День начинается с чашкой крепкого";
                    label2.Text = "виски... ";
                    trig        = true;
                    break;

                case 4:
                    label1.Text = "Кто рано встает,";
                    label2.Text = "тому на работу с утра...";
                    trig        = true;
                    break;

                case 5:
                    label1.Text = "Утро! Самое время пить...";
                    label2.Text = "Нет, не кофе, а просто пить.";
                    trig        = true;
                    break;

                case 6:
                    label1.Text = "Доброго начала дня! Сегодня тот день,";
                    label2.Text = "когда вы приблизитесь";
                    label3.Text = "к исполнению своей мечты.";
                    break;
                }
                label1.Visible = true;
                label2.Visible = true;
                string say = "";
                if (trig == true)
                {
                    label3.Visible = false;
                    say            = label1.Text + " " + label2.Text;
                }
                else
                {
                    say            = label1.Text + " " + label2.Text + " " + label3.Text;
                    label3.Visible = true;
                }
                synth.Speak(say);
            }

            if (Convert.ToInt32(bufHour) > Convert.ToInt32(day) && Convert.ToInt32(bufHour) < Convert.ToInt32(evening) || Convert.ToInt32(bufHour) == Convert.ToInt32(day))
            {
                int choice = r.Next(1, 7);
                switch (choice)
                {
                case 1:
                    label1.Text = "День в самом разгаре, а я уже устал.";
                    label2.Text = "Если вы нет, то я восхищен!";
                    break;

                case 2:
                    label1.Text = "Каждое сегодня - это новые возможности";
                    label2.Text = "для того, чтобы отложить все на завтра";
                    break;

                case 3:
                    label1.Text = "Должно быть, вы устали за утро.";
                    label2.Text = "Даже если нет, найдите время для себя любимого.";
                    break;

                case 4:
                    label1.Text = "Работа - это прекрасно. Успех вас ждет.";
                    label2.Text = "А еще я вру.";
                    break;

                case 5:
                    label1.Text = "Сегодня вас ожидает крупная удача.";
                    label2.Text = "Я уверен, удачно будет отложить свою работу.";
                    break;

                case 6:
                    label1.Text = "Вижу, вы работаете над счастьем";
                    label2.Text = "вашего начальника. Начальство одобряет! ";
                    break;
                }
                label1.Visible = true;
                label2.Visible = true;
                synth.Speak(label1.Text);
                synth.Speak(label2.Text);
            }

            if (Convert.ToInt32(bufHour) > Convert.ToInt32(night) && Convert.ToInt32(bufHour) < Convert.ToInt32(morning) || Convert.ToInt32(bufHour) == Convert.ToInt32(night))
            {
                int choice = r.Next(2, 8);
                switch (choice)
                {
                case 1:
                    label1.Text = "Чтобы сэкономить время на утренний сон,";
                    label2.Text = "я советую вам поесть ночью";
                    break;

                case 2:
                    label1.Text = "Ночь полна страхов. Но не переживайте.";
                    label2.Text = "Только утром вы почувствуете настоящий ужас.";
                    break;

                case 3:
                    label1.Text = "Делу - время, потехе час,";
                    label2.Text = "интернету - ночь, сну - не сейчас!";
                    break;

                case 4:
                    label1.Text = "Коль вредно кушать на ночь глядя,";
                    label2.Text = "закрой глаза и молча ешь!";
                    break;

                case 5:
                    label1.Text = "Если ты на ночь глядя гонял чаи, ";
                    label2.Text = "то ночью в отместку они будут гонять тебя";
                    break;

                case 6:
                    label1.Text = "Планы на ночь: 1. Прогнать кота, чтобы не мешал.";
                    label2.Text = "2. Переживать, что кот обиделся. 3. Взять кота назад";
                    break;
                }
                label1.Visible = true;
                label2.Visible = true;
                synth.Speak(label1.Text);
                synth.Speak(label2.Text);
            }
            timer1.Start();
        }
예제 #43
0
        public static async void Bot_OnMessage(object sender, MessageEventArgs e) //используем асинхронный метод чтобы поток данных не блокировался во время его получения
        {
            var    text    = e?.Message?.Text;                                    //получение текста от пользователя
            var    message = e.Message;
            string name    = $"{message.From.FirstName} {message.From.LastName}"; //получение имени пользователя

            if (message.Type == MessageType.Text)
            {                                                                                                               //проверка на тип получаемого сообщения, он должен быть текстовым
                Console.WriteLine($"Поступила инормация: '{text}' из чата: '{e.Message.Chat.Id}' от пользователя: {name}"); //проверка того что сообщения доходят до бота

                logger.Info($"Поступило сообщение: '{text}' от пользователя:  {name}");                                     //запись в лог о получении сообщения

                switch (message.Text)
                {
                case "/start":                            //команда старта бота(запускается автоматичекски при первом обращении к боту)
                    await botclient.SendTextMessageAsync( //операция вывода текущей погоды
                        chatId : e.Message.Chat,
                        text : $"Доброго времени суток! Для ознакомления с возможностями этого бота, введите команду /help"
                        ).ConfigureAwait(false);

                    break;

                case "/help":                             //показ всех доступных команд
                    await botclient.SendTextMessageAsync( //операция вывода текущей погоды
                        chatId : e.Message.Chat,
                        text : $"Доступные команды:\n/time - вывод текущего времени\n/weather - температура в Москве на данный момент\n/currency - выводиит актуальный курс доллара и евро к рублю\n/communication - вывод контактных данных для связи с разработчиком\n/joke - ультрасмешной анекдот\nЛюбой остальной текст будет озвучиватся роботизированным голосом"
                        ).ConfigureAwait(false);

                    break;

                case "/time":    //команда вывода текущего времени
                    DateTime date1 = DateTime.Now;
                    await botclient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : $"Время по Москве: {date1.ToLongTimeString()}"
                        ).ConfigureAwait(false);

                    break;

                case "/weather":                                                                                                                //команда вывода погоды
                    string url = "http://api.openweathermap.org/data/2.5/weather?q=Moscow&units=metric&appid=5c63497e9d0e4b4a8f836f11c482f278"; //берём данные их открытого источника OpenWeather, к сожалению этот сервис не предоставляет информацию по горорду Санкт-Петербург, Поэтому взял Москву
                                                                                                                                                //units=metric переводит температуру в градусы цельсия
                    HttpWebRequest  httpWebRequest  = (HttpWebRequest)WebRequest.Create(url);                                                   //обьект request для запроса
                    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();                                            //response считывает ответ с request
                    string          response;
                    using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))                                   //using для очистки используемых ресурсов
                    {
                        response = streamReader.ReadToEnd();                                                                                    //считывание текста с этого response
                    }
                    WeatherResponse weatherResponse = JsonConvert.DeserializeObject <WeatherResponse>(response);                                //поскольку данные записываются в json нужно преобразовать их в обьект c#

                    await botclient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : $"Температура в Москве: {weatherResponse.Main.Temp}°С"
                        ).ConfigureAwait(false);

                    break;

                case "/currency":                                                                       //команда вывода актуального курса валют к рублю
                    WebClient client = new WebClient();
                    var       xml    = client.DownloadString("https://www.cbr-xml-daily.ru/daily.xml"); //берём данные с Центробанка РФ
                    XDocument xdoc   = XDocument.Parse(xml);
                    var       el     = xdoc.Element("ValCurs").Elements("Valute");
                    string    dollar = el.Where(x => x.Attribute("ID").Value == "R01235").Select(x => x.Element("Value").Value).FirstOrDefault(); //берём данные по доллару
                    string    eur    = el.Where(x => x.Attribute("ID").Value == "R01239").Select(x => x.Element("Value").Value).FirstOrDefault(); //берём данные по евро

                    await botclient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : $"Курс валют к рублю на данный момент:\n Евро: {eur} Доллар: {dollar}"
                        ).ConfigureAwait(false);

                    break;

                case "/joke":    //команда вывода анекдотов
                    string[] arr = { "Мать, короче, письмо присылает пацану на кичу – типа, сынок, ты как на крытую пошёл, по хозяйству жопа. Типа уже весна пришла, надо огород перекопать, картошку и другую муйню посадить, сама ни фига не справляюсь, а ни одна сука не поможет. Пацан ей отписывает – типа, мать, оно и классно, ты огород лучше ваще не трогай, так перебейся, а то такое выкопаешь, что не тока мне срок накинут, а и тебя на крытую отправят. Матушка такая через неделю пишет – фигассе, родной, после малявы твоей последней менты вдруг набежали, весь огород перекопали, только не нашли ни хрена. Злые такие были, маты до неба гнули. А пацан ей так отвечает: типа, ну, мать, чем смог – помог, а картошку как-нить уже сама посадишь.",
                                     "Короче, сидят два пацана на крыше. Типа косячок на двоих пустили, повтыкали, потом один другому говорит так задумчиво: \n– Маза есть, короче: шмаль жизнь в два раза в натуре уменьшает. \nВторой в непонятках: \n– Это типа как? \nПервый такой: \n– Ну вот тебе лет скока ? \n– Ну, типа, двадцать пять.\n- Ну и вот.А без шмали б уже полсотни было.",
                                     "Типа идёт «Что? Где? Когда?». Ведущий такой: \n– А ща вопрос будет задавать реальный пацан Вован. \nВован: \n– Уважаемые знатоки, два месяца назад мой дружбан Колян занял у меня пять сотен и не отдал. Месяц назад Колян занял у меня три сотни и не отдал. Неделю назад он занял всего полтинник , но тоже падла не отдал... Короче, вопрос: кто лежит чёрном ящике ? ",
                                     "К Бадяну, кароче по малолетке, типа, „фея“ подвалила. Ну и гутарит: \n— Я либа мозги те дам по жизни ащще чумовые, и память такую, как у батанав внатуре, либа … ты будеш правильным пацаном „при делах“. Ну я его, типа, спрашиваю: \n— Ну и чо? \n— Ну чо чо… Я не помню чо.",
                                     "Встречаются два конкретно «подсевших» зомби: \n— Слышь, мен (томным голосом). У те есть чем догнаться? \n— Йоу, чувак! Мне тут сталкер один знакомый такую мощную штуку подогнал. Ваще. КЛАСС. \n— А как вставляет? \n— Та пять секунд и просто ОТПАД!\n— АААФИГЕТЬ. А сильно гребет?\n— Да сталкер сказал, что до полново атрыва башки! \n— УУУУ. КАЙФ.\n— Ах. А называется как?\n— А называется… ГРАНАТА.",
                                     "Подходит пацан к барыге. Типа:\n— Граната за пяторку нада?\n— Че,  ну ты гооониш. Давай!\n— Нхаа, держиии… А от за кольцо гани две сотни.",
                                     "Идёт такой военный по улице. Его мужик какой-то спрашивает:\n– Куда чешешь?\nТот такой:\n– Ты чё, мужик, охерел? Это ж, блин, военная тайна.\nМужик такой:\n– Извиняюсь, военный, попутал, не знал!А чего несёшь такое тяжёлое, что аж запрел?\nВоенный такой:\n– Да, блин, запреешь тут – патроны эти бронебойные на склад переть…",
                                     "Значит, кордон армейский на периметре. Прибыл генерал и, короче, спрашивает у салабона одного:\n– Ну, типа, сынок, как служба?\nТот так – уё-моё, да ничё типа так служба, привыкаю…\nГенерал такой:\n– Во, зелёный, зацени: ты ж теперь всех своих от Зоны защищаешь!Как сюда попал?\nТот такой:\n– Ну, короче, я согласный, шо людей в натуре надо от Зоны беречь…\nГенерал лыбится – о, блин, зашибись, сознательный попался!А тот такой дальше:\n– Я ж и военкому сто раз говорил – нефиг мне тут делать!А он, сука…",
                                     "Короче, два братана сидят трындят. Один такой:\n– Сышишь, бpатан, а чё я тебе ещё ни одной наколки не сделал? Мы ж тобой с малолетки корешаемся – вот так, как два пальчика рядом! А ну, давай я тебе на память чё-нить наколю.\nВторой такой:\n– А чё, не вопрос! Тока я сам не знаю, чё колоть.\nПервый такой:\n– А давай танк на спине!\nВторой такой:\n– Ну танк, так танк, ничё так тема... Тока чтоб красиво, сечёшь?\nТот такой:\n– Обижаешь! Опупенно будет, зуб даю!\nИ, короче, пpоходит пять минут.Кольщик такой:\n– Зашибись! Готово.\nВторой такой:\n– Фигассе, чё так быстро?\nКольщик такой:\n– А хуле, там всего четыре буквы.",
                                     "Папа съел флешку, и теперь он ПАПКА С ФАЙЛАМИ.",
                                     "— Почему в Африке так много болезней?\n— Потому что таблетки нужно запивать водой.",
                                     "Встречаютя как то мужики. Один другому говорит:\n-Здарова. У меея 2 новости, хорошая и плохая. С какой начать?\nВторой и отвечает:\n-Ну давай с плохой.\n-Жену твою наши в реке утонула.\n-А хорошая какая?\n-Мы с неё ведро раков наловили" };
                    await botclient.SendTextMessageAsync(
                        chatId : e.Message.Chat,
                        text : arr[new Random().Next(0, arr.Length)]
                        ).ConfigureAwait(false);

                    break;

                case "/communication":    //команда выводящая контакты разработчика
                    var inlinekeyboard = new InlineKeyboardMarkup(new[]
                    {
                        InlineKeyboardButton.WithUrl("VK", "https://vk.com/lukyanchic"),      //кнопка с ссылкой на вк
                        InlineKeyboardButton.WithUrl("Telegram", "https://t.me/KiberPaladin") //кнопка с ссылкой на телеграм
                    });
                    await botclient.SendTextMessageAsync(message.From.Id, "Связь с разработчиком", replyMarkup : inlinekeyboard).ConfigureAwait(false);

                    break;

                default:                                                                 //в этом блоке будут озвучиватся текст не являющийся командами
                    SpeechSynthesizer speechSynth = new SpeechSynthesizer();             //создаём объект

                    speechSynth.Volume = 100;                                            //устанавливаем уровень звука

                    speechSynth.SelectVoiceByHints(VoiceGender.Neutral, VoiceAge.Adult); //также можно устанавливать пол и возвраст озвучки
                    speechSynth.Speak(text);
                    break;
                }
            }
            else if (message.Type == MessageType.Voice)//добавляю реакцию на голосовые сообщения
            {
                logger.Info("Поступило голосовое сообщение от пользователя");
                await botclient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : $"Ненавижу голосовые сообщения >:("
                    ).ConfigureAwait(false);

                Console.WriteLine($"Поступило голосовое сообщение из чата: '{e.Message.Chat.Id}' от пользователя: {name}");//проверка того что сообщения доходят до бота
            }
            else
            {
                return;
            }
        }
예제 #44
0
 private void Form1_Load(object sender, System.EventArgs e)
 {
     speechSynthesizerObj = new SpeechSynthesizer();
     speechSynthesizerObj.Speak("Welcome to the 4 column shopping list");
 }
예제 #45
0
        public async Task OpenTextSpeechUI(Domain.ViewModels.Guide guideToRead)
        {
            try
            {
                ObservableCollection <GuideBasePage> pagesToRead = guideToRead.Items;

                SpeechSynthesizer synth = new SpeechSynthesizer();
                var voices = InstalledVoices.All.Where(o => o.Language.StartsWith("en"));

                if (voices.Count() > 0)
                {
                    synth.SetVoice(voices.First());

                    guideToRead.BeingRead = true;


                    if (guideToRead.SelectedPageIndex == 0)
                    {
                        var toRead = ((GuideIntro)pagesToRead[0]);
                        if (!string.IsNullOrEmpty(toRead.Subject))
                        {
                            task = synth.SpeakTextAsync(toRead.Subject);
                            await task;
                        }
                        if (!string.IsNullOrEmpty(toRead.Summary))
                        {
                            task = synth.SpeakTextAsync(toRead.Summary);
                            await task;
                        }

                        guideToRead.SelectedPageIndex = 1;
                    }


                    for (int i = guideToRead.SelectedPageIndex; i < pagesToRead.Count; i++)
                    {
                        if (guideToRead.BeingRead == false)
                        {
                            break;
                        }

                        guideToRead.SelectedPage = (GuideBasePage)pagesToRead[i];

                        guideToRead.SelectedPageIndex = guideToRead.Items.IndexOf(guideToRead.SelectedPage);

                        var item = (GuideStepItem)pagesToRead[i];
                        int m    = 0;

                        foreach (var line in item.Lines)
                        {
                            if (guideToRead.BeingRead == false)
                            {
                                break;
                            }

                            guideToRead.SelectedStepLine = m;
                            try
                            {
                                task = synth.SpeakTextAsync(line.VoiceText);
                                await task;
                            }
                            catch (Exception ex)
                            {
                                //  throw;
                            }
                            m++;
                        }
                    }

                    guideToRead.BeingRead = false;
                }
                else
                {
                    MessageBox.Show("please install the english voice languague pack ");
                }
            }
            catch (Exception)
            {
            }
        }
예제 #46
0
파일: Speech.cs 프로젝트: siwanghu/USTC
 private Speech()
 {
     Volume      = 100;
     Rate        = 1;
     synthesizer = new SpeechSynthesizer();
 }
예제 #47
0
 public Larynx()
 {
     voiceON = true;
     synth   = new SpeechSynthesizer();
     synth.SetOutputToDefaultAudioDevice();
 }
예제 #48
0
        public void HandleCommunication()
        {
            _sReader = new StreamReader(_client.GetStream(), Encoding.ASCII);
            _sWriter = new StreamWriter(_client.GetStream(), Encoding.ASCII);

            _isConnected = true;
            String sData = null;

            while (_client.Connected)
            {
                //Console.Write("&gt; ");
                //sData = Console.ReadLine();

                // write data and make sure to flush, or the buffer will continue to
                // grow, and your data might not be sent when you want it, and will
                // only be sent once the buffer is filled.
                //_sWriter.WriteLine(sData);
                //_sWriter.Flush();

                // if you want to receive anything
                String sDataIncomming = null;
                try
                {
                    sDataIncomming = _sReader.ReadLine();
                    dataTab        = new string[1];
                    dataTab        = sDataIncomming.Split('_');
                    if (dataTab[1] == "1")
                    {
                        MessageBox.Show(dataTab[0], "server", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    if (dataTab[1] == "2")
                    {
                        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
                        synthesizer.Volume = 70;
                        synthesizer.SpeakAsync(dataTab[0]);
                    }
                    if (dataTab[1] == "5")
                    {
                        if (dataTab[0] == "true")
                        {
                            BlockInput(true);
                        }
                        else
                        {
                            BlockInput(false);
                        }
                    }
                    if (dataTab[1] == "7")
                    {
                        Process.Start("shutdown.exe", "-s -t 0");
                    }
                    if (dataTab[1] == "8")
                    {
                        Process.Start("shutdown.exe", "-r -t 0");
                    }
                    if (dataTab[1] == "9")
                    {
                        Process.Start("shutdown.exe", "-l -t 0");
                    }
                    if (dataTab[1] == "10")
                    {
                        int hwnd = FindWindow("Shell_TrayWnd", "");
                        ShowWindow(hwnd, SW_HIDE);
                    }
                    if (dataTab[1] == "11")
                    {
                        int hwnd = FindWindow("Shell_TrayWnd", "");
                        ShowWindow(hwnd, SW_SHOW);
                    }
                    if (dataTab[1] == "12")
                    {
                        rd = true;
                        Thread tRD = new Thread(startRD);
                        tRD.Start();
                    }
                    if (dataTab[1] == "13")
                    {
                        rd = false;
                    }
                    if (dataTab[1] == "14")
                    {
                        wc = true;
                        Thread WC = new Thread(() => startWebCam(dataTab[0]));
                        WC.Start();
                    }
                    if (dataTab[1] == "15")
                    {
                        wc = false;
                        stopWebcam();
                    }
                    if (dataTab[1] == "16")
                    {
                        string webcamNames = null;
                        VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                        foreach (FilterInfo VideoCaptureDevice in VideoCaptureDevices)
                        {
                            webcamNames += VideoCaptureDevice.Name + "_";
                        }
                        _sWriter.WriteLine(webcamNames);
                        _sWriter.Flush();
                    }
                    if (dataTab[1] == "17")
                    {
                        Process p = Process.Start("notepad.exe");
                        p.WaitForInputIdle();
                        IntPtr h = p.MainWindowHandle;
                        SetForegroundWindow(h);
                        try
                        {
                            for (int i = 0; i < dataTab[0].Length; i++)
                            {
                                SendKeys.SendWait(dataTab[0][i].ToString());
                                Thread.Sleep(50);
                            }
                        }
                        catch
                        {
                            SendKeys.SendWait("Hello men, i see you");
                        }
                    }
                    if (dataTab[1] == "18")
                    {
                        try
                        {
                            foreach (DriveInfo drive in DriveInfo.GetDrives())
                            {
                                if (drive.DriveType == DriveType.CDRom)
                                {
                                    cd.openDrive(drive.RootDirectory.ToString());
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    if (dataTab[1] == "19")
                    {
                        try
                        {
                            foreach (DriveInfo drive in DriveInfo.GetDrives())
                            {
                                if (drive.DriveType == DriveType.CDRom)
                                {
                                    cd.closeDrive(drive.RootDirectory.ToString());
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                    //if (dataTab[1] == "20")
                    //{
                    MouseClick(false);
                    //}
                    if (dataTab[1] == "21")
                    {
                        MouseClick(true);
                    }
                }
                catch
                {
                    //Application.Restart();
                }
            }
        }
예제 #49
0
        private async void webBrowser1_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.Equals(webBrowser1.Url))
            {
                if (SwearGenerator.GlobalVars.instances == 1)
                {
                    await LoadingTime(2000);

                    SwearGenerator.GlobalVars.generateStatus = "Working - Generating SwearWord";
                    Console.WriteLine("Now it is really done");
                    webBrowser1.Document.ExecCommand("SelectAll", false, null);
                    webBrowser1.Document.ExecCommand("Copy", false, null);
                    Properties.Settings.Default.lastSwear = Clipboard.GetText();
                    Console.WriteLine(Properties.Settings.Default.lastSwear);
                    Properties.Settings.Default.lastSwear = ReadLine(Properties.Settings.Default.lastSwear, 26);
                    SwearGenerator.GlobalVars.sessionGenerated.Add(Properties.Settings.Default.lastSwear);

                    SpeechSynthesizer synthesizer = new SpeechSynthesizer();
                    synthesizer.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Adult);
                    synthesizer.Volume = 100;  // 0...100
                    synthesizer.Rate   = -2;   // -10...10

                    // Asynchronous
                    Console.WriteLine(Properties.Settings.Default.lastSwear);
                    Console.WriteLine("synth");
                    synthesizer.SpeakAsync(Properties.Settings.Default.lastSwear);
                    MessageBox.Show(Properties.Settings.Default.lastSwear);
                    if (SwearGenerator.GlobalVars.clipboard == 1)
                    {
                        System.Windows.Forms.Clipboard.SetText(Properties.Settings.Default.lastSwear);
                    }
                }
                else
                {
                    for (int i = 0; i < SwearGenerator.GlobalVars.instances; i++)
                    {
                        if (i >= 1)
                        {
                            webBrowser1.Refresh(); await LoadingTime(2000);
                        }
                        else
                        {
                            await LoadingTime(2000);
                        }
                        string instances =
                            SwearGenerator.GlobalVars.generateStatus = "Working - Generating " + (i + 1) + " out of " + SwearGenerator.GlobalVars.instances.ToString();
                        Console.WriteLine("Now it is really done");
                        webBrowser1.Document.ExecCommand("SelectAll", false, null);
                        webBrowser1.Document.ExecCommand("Copy", false, null);
                        Properties.Settings.Default.lastSwear = Clipboard.GetText();
                        Console.WriteLine(Properties.Settings.Default.lastSwear);
                        Properties.Settings.Default.lastSwear = ReadLine(Properties.Settings.Default.lastSwear, 26);
                        SwearGenerator.GlobalVars.sessionGenerated.Add(Properties.Settings.Default.lastSwear);
                    }
                    SwearGenerator.GlobalVars.generateStatus = "Done! - Generated " + SwearGenerator.GlobalVars.instances.ToString() + " SwearWords, Have Fun!";
                    string tempgen = "Words generated this session:\n";
                    foreach (string j in SwearGenerator.GlobalVars.sessionGenerated)
                    {
                        tempgen += ("\n\t" + j);
                    }
                    SwearGenerator.GlobalVars.generateStatus = "Working - Saving new SwearWords";

                    /* foreach (string k in SwearGenerator.GlobalVars.sessionGenerated)
                     * {
                     * Properties.Settings.Default.allSwearsGenerated.Add(k);
                     * }*/
                    //Properties.Settings.Default.Save();

                    SpeechSynthesizer synthesizer = new SpeechSynthesizer();
                    synthesizer.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Adult);
                    synthesizer.Volume = 100;      // 0...100
                    synthesizer.Rate   = -2;       // -10...10

                    // Asynchronous
                    Console.WriteLine(tempgen);
                    Console.WriteLine("synth");
                    synthesizer.SpeakAsync(tempgen);
                    MessageBox.Show(tempgen);

                    SwearGenerator.GlobalVars.sessionGenerated.Clear();
                    SwearGenerator.GlobalVars.generateStatus = "Idle - Waiting";
                }
            }
        }
예제 #50
0
    public static void Main()
    {
        Console.OutputEncoding = Encoding.GetEncoding("UTF-8");
        Console.CursorVisible  = false;
        ConsoleColor originalColor = Console.ForegroundColor;

        Console.CursorLeft   = 0;
        Console.WindowHeight = 50;
        Console.WindowWidth  = 115;

        StreamReader screen = new StreamReader(@"..\..\media\Screen.txt");

        try
        {
            using (screen)
            {
                List <string> startScreen = new List <string>();
                string        reader      = screen.ReadLine();
                while (reader != null)
                {
                    startScreen.Add(reader);
                    reader = screen.ReadLine();
                }

                //TODO someday:
                //http://stackoverflow.com/questions/5805774/how-to-generate-random-color-names-in-c-sharp
                //Use Enum.GetValue to retrieve the values of the KnownColor enumeration and get a random value.

                Console.WriteLine("\n");

                Console.ForegroundColor = ConsoleColor.Green;
                for (int i = 8; i < 12; i++)
                {
                    Console.WriteLine(startScreen[i]);
                }

                Console.ForegroundColor = ConsoleColor.Magenta;
                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine(startScreen[i]);
                }

                Console.ForegroundColor = ConsoleColor.Green;
                for (int i = 8; i < 12; i++)
                {
                    Console.WriteLine(startScreen[i]);
                }

                Console.WriteLine("\n");
                SpeechSynthesizer synth = new SpeechSynthesizer();
                synth.SetOutputToDefaultAudioDevice();
                synth.Speak("happy      birthday      dad");

                SoundPlayer simpleSound = new SoundPlayer(@"..\..\media\HappyBirthdayBeeps.wav");
                simpleSound.Play();

                Thread.Sleep(300);

                ////poem
                Console.ForegroundColor = ConsoleColor.Yellow;
                for (int i = 14; i < 32; i++)
                {
                    Console.WriteLine(startScreen[i]);
                    if (i < 25)
                    {
                        Thread.Sleep(600);
                    }
                    else
                    {
                    }
                }

                Thread.Sleep(3500);
                Console.Clear();
                Console.WriteLine("\n");

                Console.ForegroundColor = ConsoleColor.Green;
                for (int i = 8; i < 12; i++)
                {
                    Console.WriteLine(startScreen[i]);
                }

                Console.ForegroundColor = ConsoleColor.Magenta;
                for (int i = 0; i < 8; i++)
                {
                    Console.WriteLine(startScreen[i]);
                }

                Console.ForegroundColor = ConsoleColor.Green;
                for (int i = 8; i < 12; i++)
                {
                    Console.WriteLine(startScreen[i]);
                }

                Console.ForegroundColor = ConsoleColor.Yellow;
                for (int i = 32; i < 70; i++)
                {
                    Console.WriteLine(startScreen[i]);
                }

                Thread.Sleep(8000);
                for (int i = 72; i < 122; i++)
                {
                    Thread.Sleep(100);
                    Console.WriteLine(startScreen[i]);
                    Console.ForegroundColor = ConsoleColor.Green;
                }
            }
        }
        catch (FileNotFoundException)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Can't not find the loading screen file!");
        }
        catch (DirectoryNotFoundException)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("The path to the loading screen file is incorrect!");
        }
        catch (IOException)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Error with the loading screen file!");
        }
    }
예제 #51
0
 private void InitializeSynthesizer()
 {
     speechSynthesizer = new SpeechSynthesizer();
 }
예제 #52
0
        // Speech synthesis to audio data stream.
        public static async Task SynthesisToAudioDataStreamAsync()
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");

            // Creates a speech synthesizer with a null output stream.
            // This means the audio output data will not be written to any stream.
            // You can just get the audio from the result.
            using (var synthesizer = new SpeechSynthesizer(config, null as AudioConfig))
            {
                while (true)
                {
                    // Receives a text from console input and synthesize it to result.
                    Console.WriteLine("Enter some text that you want to synthesize, or enter empty text to exit.");
                    Console.Write("> ");
                    string text = Console.ReadLine();
                    if (string.IsNullOrEmpty(text))
                    {
                        break;
                    }

                    using (var result = await synthesizer.SpeakTextAsync(text))
                    {
                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            Console.WriteLine($"Speech synthesized for text [{text}].");

                            using (var audioDataStream = AudioDataStream.FromResult(result))
                            {
                                // You can save all the data in the audio data stream to a file
                                string fileName = "outputaudio.wav";
                                await audioDataStream.SaveToWaveFileAsync(fileName);

                                Console.WriteLine($"Audio data for text [{text}] was saved to [{fileName}]");

                                // You can also read data from audio data stream and process it in memory
                                // Reset the stream position to the beginnging since saving to file puts the postion to end
                                audioDataStream.SetPosition(0);

                                byte[] buffer     = new byte[16000];
                                uint   totalSize  = 0;
                                uint   filledSize = 0;

                                while ((filledSize = audioDataStream.ReadData(buffer)) > 0)
                                {
                                    Console.WriteLine($"{filledSize} bytes received.");
                                    totalSize += filledSize;
                                }

                                Console.WriteLine($"{totalSize} bytes of audio data received for text [{text}]");
                            }
                        }
                        else if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                            Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                            if (cancellation.Reason == CancellationReason.Error)
                            {
                                Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                                Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                                Console.WriteLine($"CANCELED: Did you update the subscription info?");
                            }
                        }
                    }
                }
            }
        }
예제 #53
0
        void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
        {
            try
            {
                string      message            = Encoding.UTF8.GetString(e.Message);
                mqtttrigger CurrentMqttTrigger = new mqtttrigger();
                WriteToLog("Message recived " + e.Topic + " value " + message);

                string TopLevel = Properties.Settings.Default["mqtttopic"].ToString().Replace("/#", "");
                string subtopic = e.Topic.Replace(TopLevel + "/", "");

                foreach (mqtttrigger tmpTrigger in MqttTriggerList)
                {
                    if (tmpTrigger.name == subtopic)
                    {
                        CurrentMqttTrigger    = tmpTrigger;
                        CurrentMqttTrigger.id = 1;
                        break;
                    }
                }

                if (CurrentMqttTrigger.id == 1)
                {
                    switch (subtopic)
                    {
                    case "app/running":
                        MqttPublish(SetSubTopic("app/running/" + message), ExeRunning(message, ""));
                        break;

                    case "app/close":
                        MqttPublish(SetSubTopic("app/running/" + message), ExeClose(message));
                        break;

                    case "monitor/set":

                        using (var f = new Form())
                        {
                            if (message == "1")
                            {
                                NativeMethods.SendMessage(f.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MonitorTurnOn);
                                MqttPublish(SetSubTopic("monitor"), "1");
                            }
                            else
                            {
                                NativeMethods.SendMessage(f.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)MonitorShutoff);
                                MqttPublish(SetSubTopic("monitor"), "0");
                            }
                        }
                        break;

                    case "mute/set":

                        if (message == "1")
                        {
                            audioobj.Mute(true);
                        }
                        else
                        {
                            audioobj.Mute(false);
                        }

                        MqttPublish(TopLevel + "/mute", message);
                        break;

                    case "mute":
                        break;

                    case "volume":
                        break;

                    case "volume/set":
                        audioobj.Volume(Convert.ToInt32(message));
                        break;

                    case "hibernate":
                        Application.SetSuspendState(PowerState.Hibernate, true, true);
                        break;

                    case "suspend":
                        Application.SetSuspendState(PowerState.Suspend, true, true);
                        break;

                    case "reboot":
                        System.Diagnostics.Process.Start("shutdown.exe", "-r -t 10");
                        break;

                    case "shutdown":
                        System.Diagnostics.Process.Start("shutdown.exe", "-s -t 10");
                        break;

                    case "tts":
                        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
                        // synthesizer.GetInstalledVoices

                        synthesizer.Volume = 100;      // 0...100
                        synthesizer.SpeakAsync(message);
                        break;

                    case "toast":

                        int i = 0;

                        string Line1   = "";
                        string Line2   = "";
                        string Line3   = "";
                        string FileURI = "";

                        string[] words = message.Split(',');
                        foreach (string word in words)
                        {
                            switch (i)
                            {
                            case 0:
                                Line1 = word;
                                break;

                            case 1:
                                Line2 = word;
                                break;

                            case 2:
                                Line3 = word;
                                break;

                            case 3:
                                FileURI = word;
                                break;

                            default:
                                break;
                            }
                            i = i + 1;
                        }
                        Toastmessage(Line1, Line2, Line3, FileURI, ToastTemplateType.ToastImageAndText04);


                        break;

                    default:

                        if (CurrentMqttTrigger.cmdtext.Length > 2)
                        {
                            ProcessStartInfo startInfo = new ProcessStartInfo(CurrentMqttTrigger.cmdtext);
                            startInfo.WindowStyle = ProcessWindowStyle.Maximized;
                            if (CurrentMqttTrigger.cmdparameters.Length > 2)
                            {
                                startInfo.Arguments = CurrentMqttTrigger.cmdparameters;
                            }
                            Process.Start(startInfo);
                        }

                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToLog("error: " + ex.Message);
            }
        }
예제 #54
0
        static void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            //Speaker
            SpeechSynthesizer speaker = new SpeechSynthesizer();

            speaker.SetOutputToDefaultAudioDevice();

            Console.WriteLine("Matched");
            float conf = e.Result.Confidence;
            int   c;

            //General Communication
            c = string.Compare(e.Result.Text.ToString(), "hello");
            if (c == 0)
            {
                speaker.Speak("Hello. Welcome to Connexions 2014");
            }

            c = string.Compare(e.Result.Text.ToString(), "hey");
            if (c == 0)
            {
                speaker.Speak("Hey");
            }

            c = string.Compare(e.Result.Text.ToString(), "hi");
            if (c == 0)
            {
                speaker.Speak("Hi!");
            }

            c = string.Compare(e.Result.Text.ToString(), "how are you");
            if (c == 0)
            {
                speaker.Speak("I am good. How are you");
            }

            c = string.Compare(e.Result.Text.ToString(), "kese ho");
            if (c == 0)
            {
                speaker.Speak("I am good. How are you");
            }

            c = string.Compare(e.Result.Text.ToString(), "what is your name");
            if (c == 0)
            {
                speaker.Speak("My name is TurtleBot. But you can call me Chhutu");
            }

            c = string.Compare(e.Result.Text.ToString(), "who has programmed you");
            if (c == 0)
            {
                speaker.Speak("Imran, Nabeel and Safeer. has programmed me");
            }

            c = string.Compare(e.Result.Text.ToString(), "tell me about yourself");
            if (c == 0)
            {
                speaker.Speak("I am Turtlebot. I am running on ROS. I participated in Eraan Open 2014 Competition. I met with other robots there");
            }

            c = string.Compare(e.Result.Text.ToString(), "nice to meet you");
            if (c == 0)
            {
                speaker.Speak("Thank you. Same here");
            }

            c = string.Compare(e.Result.Text.ToString(), "tell me about your features");
            if (c == 0)
            {
                speaker.Speak("My features are: I can talk. I can recognise faces. I can recognise colors. I can learn any path");
            }

            //General Communication Ends

            //------------------------------------------//

            //Commands
            c = string.Compare(e.Result.Text.ToString(), "chotu wake up");
            if (c == 0)
            {
                speaker.Speak("Hi! I am Listening");
                data  = 6;
                awake = 1;
            }

            if (awake == 1)
            {
                c = string.Compare(e.Result.Text.ToString(), "chotu stop");
                if (c == 0)
                {
                    speaker.Speak("Stopping");
                    data = 1;
                }

                c = string.Compare(e.Result.Text.ToString(), "bus ruk jao");
                if (c == 0)
                {
                    speaker.Speak("Ok!");
                    data = 1;
                }

                c = string.Compare(e.Result.Text.ToString(), "chotu forward");
                if (c == 0)
                {
                    data = 2;
                    speaker.Speak("Moving Forward");
                }

                c = string.Compare(e.Result.Text.ToString(), "chotu backward");
                if (c == 0)
                {
                    speaker.Speak("Moving Backward");
                    data = 3;
                }
                c = string.Compare(e.Result.Text.ToString(), "chotu right");
                if (c == 0)
                {
                    speaker.Speak("Turning Right");
                    data = 4;
                }
                c = string.Compare(e.Result.Text.ToString(), "chotu left");
                if (c == 0)
                {
                    speaker.Speak("Turning Left");
                    data = 5;
                }
                c = string.Compare(e.Result.Text.ToString(), "chotu sleep");
                if (c == 0)
                {
                    speaker.Speak("Ok. Sleeping now. Bye Bye");
                    data  = 7;
                    awake = 0;
                }
                c = string.Compare(e.Result.Text.ToString(), "face count");
                if (c == 0)
                {
                    data = 8;

                    //if (count_t == 0)
                    {
                        //Thread
                        ThreadStart childref2    = new ThreadStart(worker2);
                        Thread      childThread2 = new Thread(childref2);
                        childThread2.Start();
                        //Thread
                    }
                    count_t++;
                }
                c = string.Compare(e.Result.Text.ToString(), "face follow");
                if (c == 0)
                {
                    speaker.Speak("Following");
                    data = 9;
                }

                c = string.Compare(e.Result.Text.ToString(), "pattern follow");
                if (c == 0)
                {
                    speaker.Speak("Following");
                    data = 10;
                }
            }
        }
예제 #55
0
        private static void Main(string[] args)
        {
            string            appversion             = "v2.1.0";
            bool              StringIsNotM8BQuestion = false;
            DateTime          today             = DateTime.Today;
            SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
            ConsoleColor      foregroundColor   = Console.ForegroundColor;

            Program.Setup();
            Console.Clear();
            Program.Setup2();
            Console.ForegroundColor = foregroundColor;
            Random random = new Random();
            bool   flag   = false;

            while (true)
            {
                string   NNDay  = "12/14/2017";
                DateTime nnday  = Convert.ToDateTime(NNDay);
                bool     flag26 = !flag;
                if (flag26)
                {
                    bool flag27 = today == nnday;
                    if (flag27)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Today is the final fight for Net Neutrality in 2017");
                        Console.WriteLine("DO NOT LET ANYTHING STAND IN THE WAY OF YOUR FIGHT!");
                        Console.WriteLine();
                        flag = true;
                    }
                }

                string   AprilFools = "4/01";
                DateTime d          = Convert.ToDateTime(AprilFools);

                bool flag2 = !flag;
                if (flag2)
                {
                    bool flag3 = today == d;
                    if (flag3)
                    {
                        Program.rickroll();
                        flag = true;
                        Console.WriteLine("You got rickrolled (in the original YouTube sense). Happy April Fools!");
                    }
                }
                string text = Program.ua();
                Console.ForegroundColor = ConsoleColor.Red;
                int          num = random.Next(5) + 1;
                ConsoleColor foregroundColor2 = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Cyan;
                switch (random.Next(4))
                {
                case 0:
                    Console.WriteLine("Thinking...");
                    break;

                case 1:
                    Console.WriteLine("Aligning stars...");
                    break;

                case 2:
                    Console.WriteLine("Contacting mages...");
                    break;

                case 3:
                    Console.WriteLine("Deciphering the universe...");
                    break;
                }
                Thread.Sleep(num * 1000);
                Console.ForegroundColor = foregroundColor2;

                // This is where the process of determining the proper response to user input begins.
                // It will first compare the user string to that of those with predefined separate actions.
                // If the uuser's input does not correlate with any of these, the response will be one of the
                // Magic 8 Ball's random answers.

                bool flag25 = text.ToLower() == "long live";
                if (flag25)
                {
                    Console.WriteLine("LONG LIVE SEAN PATRICK MALONEY!!");
                    StringIsNotM8BQuestion = true;
                }

                bool flag24 = text.ToLower() == "69";
                if (flag24)
                {
                    Console.WriteLine("Best number in the universe!");
                    speechSynthesizer.Speak("Best number in the universe!");
                    StringIsNotM8BQuestion = true;
                }

                bool flag23 = text.ToLower() == "version";
                if (flag23)
                {
                    Console.WriteLine(appversion);
                    speechSynthesizer.Speak("You are currently using version" + appversion + "of Levi's Magic 8 Ball");
                    StringIsNotM8BQuestion = true;
                }

                bool flag22 = text.ToLower() == "oh dear lord";
                if (flag22)
                {
                    // Jukebox: plays "XTC - Dear God"
                    Console.WriteLine("What lord?");
                    speechSynthesizer.Speak("What lord?");
                    new Process
                    {
                        StartInfo =
                        {
                            FileName = "https://www.youtube.com/watch?v=IHmTqoLjlXo"
                        }
                    }.Start();
                    StringIsNotM8BQuestion = true;
                }

                bool flag21 = text.ToLower() == "animals wearing clothes";
                if (flag21)
                {
                    // Jukebox: Plays "The Deadly Syndrome - Animals Wearing Clothes"
                    Console.WriteLine("This was poorly planned, and executed twice as bad...");
                    speechSynthesizer.Speak("This was poorly planned, and executed twice as bad...");
                    new Process
                    {
                        StartInfo =
                        {
                            FileName = "https://www.youtube.com/watch?v=u6ENZhap-PY"
                        }
                    }.Start();
                    StringIsNotM8BQuestion = true;
                }

                bool flag20 = text.ToLower() == "spin me round";
                if (flag20)
                {
                    // Jukebox: Plays "Dead or Alive - You Spin Me Round (Like a Record)"
                    Console.WriteLine("You spin me round round baby round round like a record baby right round round round.");
                    speechSynthesizer.Speak("You spin me round round baby round round like a record baby right round round round.");
                    new Process
                    {
                        StartInfo =
                        {
                            FileName = "https://www.youtube.com/watch?v=PGNiXGX2nLU"
                        }
                    }.Start();
                    StringIsNotM8BQuestion = true;
                }

                bool flag19 = text.ToLower() == "enjoy yourself";
                if (flag19)
                {
                    // Jukebox: Plays "SAINT PEPSI - Enjoy Yourself"
                    Console.WriteLine("I've been doing that for a long time now, and I think it's time for you to get a chance at enjoying yourself!");
                    speechSynthesizer.Speak("I've been doing that for a long time now, and I think it's time for you to get a chance at enjoying yourself!");
                    new Process
                    {
                        StartInfo =
                        {
                            FileName = "https://www.youtube.com/watch?v=_hI0qMtdfng"
                        }
                    }.Start();
                    StringIsNotM8BQuestion = true;
                }
                bool flag18 = text.ToLower() == "what's in the cut?";
                if (flag18)
                {
                    // Jukebox: Plays "K. Flay - Blood In The Cut (Official Video)"
                    Console.WriteLine("Blood is in the cut, of course. As is with all cuts, mental and physical.");
                    speechSynthesizer.Speak("Blood is in the cut, of course. As is with all cuts, mental and physical.");

                    new Process
                    {
                        StartInfo =
                        {
                            FileName = "https://www.youtube.com/watch?v=k2WcOdz96ko"
                        }
                    }.Start();
                    StringIsNotM8BQuestion = true;
                }
                bool flag17 = text.ToLower() == "give me something to believe in";
                if (flag17)
                {
                    // Jukebox: Plays "Young The Giant - Something To Believe In (Official Video)"
                    Console.WriteLine("Okay, I'll try. It's going to be difficult if you are an Atheist and against Trump, though.");
                    speechSynthesizer.Speak("Okay, I'll try. It's going to be difficult if you are an atheist and against Trump, though.");
                    new Process
                    {
                        StartInfo =
                        {
                            FileName = "https://www.youtube.com/watch?v=m_ZRWZv14SA"
                        }
                    }.Start();
                    StringIsNotM8BQuestion = true;
                }
                bool flag16 = text.ToLower() == "make me a believer";
                if (flag16)
                {
                    // Jukebox: Plays "Imagine Dragons - Believer (Official Video)"
                    Console.WriteLine("I'll try to make you a believer... hopefully in science!");
                    speechSynthesizer.Speak("I'll try to make you a believer... hopefully in science!");
                    new Process
                    {
                        StartInfo =
                        {
                            FileName = "https://www.youtube.com/watch?v=7wtfhZwyrcc"
                        }
                    }.Start();
                    StringIsNotM8BQuestion = true;
                }
                bool flag4 = text.ToLower() == "clear";
                if (flag4)
                {
                    Console.Clear();
                    Program.Setup2();
                    StringIsNotM8BQuestion = true;
                }
                bool flag5 = text.ToLower() == "rickroll";
                if (flag5)
                {
                    // Either for prank or listening purposes, plays "Rick Astley - Never Gonna Give You Up"
                    Console.WriteLine("Do you actually like this, or are you pranking somebody?");
                    speechSynthesizer.Speak("Do you actually like this, or are you pranking somebody?");
                    Program.rickroll();
                    StringIsNotM8BQuestion = true;
                }

                //This short section deals with humans and human relationships, should somebody use this M8B
                //to solve them for some reason. Humans are weird, and being one myself, I do have room to talk

                bool flag6 = text.ToLower() == "will levi go out with me?";
                if (flag6)
                {
                    // Explains Levi's Relationship Status, whatever it is at most recent update. This
                    // comment will always remain as is for simplicity.

                    Console.Clear();
                    ConsoleColor PreMsgFG = Console.ForegroundColor;
                    ConsoleColor PreMsgBG = Console.BackgroundColor;
                    Console.BackgroundColor = ConsoleColor.DarkBlue;
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("I don't know, as of about 1/20/17, he's attempting to impress a girl named Naomi Post. As of 8/04/2017, ");
                    Console.WriteLine("She's gone out with him one time, but she could be thinking of that on a friend-level.");
                    Console.WriteLine(" Social Things have always confused him, but he's trying to make this work. Levi is currently trying");
                    Console.WriteLine("to find a way to see what she considers the movie event to be without possibly misphrasing.");
                    Console.WriteLine("His explanations suuuck, which is why he hasn't asked about it yet. He did, however, ask the quality of the event.");
                    Console.WriteLine("This part seems to be satisfactory, but Levi also sucks at social situations in which a hidden message may exist.");
                    Console.WriteLine();
                    Console.WriteLine("Naomi, if you somehow found this on your own, I congratulate you decompiling/reverse engineering an application!");
                    Console.WriteLine("I hope that I have not misinterpreted anything, and if I have, please just say so.");
                    Console.WriteLine("Also, it would be awesome if you told me that you successfully decompiled an app. You're especially awesome if");
                    Console.WriteLine("you did, and I'd be stunned at this if you say so. It would also be rather inetersting if you legitimately asked");
                    Console.WriteLine("the magic 8 ball this to find it. What are the chances of that? Anyways, yeah I'd love to go out with you again sometime!");
                    Console.ForegroundColor = PreMsgFG;
                    Console.BackgroundColor = PreMsgBG;
                    StringIsNotM8BQuestion  = true;
                }
                bool flag7 = text.ToLower() == "will he go out with me?";
                if (flag7)
                {
                    Console.Clear();
                    ConsoleColor foregroundColor3 = Console.ForegroundColor;
                    ConsoleColor backgroundColor  = Console.BackgroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.BackgroundColor = ConsoleColor.DarkBlue;
                    Console.WriteLine("What do you think? Go ask him (unless it's Levi Collinsworth, he's taken!)");
                    Console.ForegroundColor = foregroundColor3;
                    Console.BackgroundColor = backgroundColor;
                    StringIsNotM8BQuestion  = true;
                }

                bool flag8 = text.ToLower() == "will she go out with me?";
                if (flag8)
                {
                    Console.Clear();
                    ConsoleColor foregroundColor4 = Console.ForegroundColor;
                    ConsoleColor backgroundColor2 = Console.BackgroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.BackgroundColor = ConsoleColor.DarkBlue;
                    Console.WriteLine("There's no instant way to know.");
                    Console.WriteLine("A general rule of thumb is that you should ask her while she's alone,");
                    Console.WriteLine("because you want to hear what she's got to say, not her friends. Make");
                    Console.WriteLine("sure that you are well-groomed before asking, though. This includes  ");
                    Console.WriteLine("well-trimmed nails, a fresh haircut, shaved facial hair, etc. In the ");
                    Console.WriteLine("end, it takes confidence to ask, too, so get all the previous done as");
                    Console.WriteLine("much/early as possible. Last thing she wants to hear is \"I would've,");
                    Console.WriteLine("but I 'didn't get the chance'.\" Avoid that as much as possible. No, ");
                    Console.WriteLine("ALWAYS avoid that. But do those things and then ask while she's alone.");
                    Console.ForegroundColor = foregroundColor4;
                    Console.BackgroundColor = backgroundColor2;
                    StringIsNotM8BQuestion  = true;
                }
                bool flag9 = text.ToLower() == "what did trump say to the obama supporters?";
                if (flag9)
                {
                    ConsoleColor foregroundColor5 = Console.ForegroundColor;
                    ConsoleColor backgroundColor3 = Console.BackgroundColor;
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.Write("Orange");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write(" is the new");
                    Console.ForegroundColor = ConsoleColor.Black;
                    Console.BackgroundColor = ConsoleColor.White;
                    Console.WriteLine(" Black");
                    Console.ForegroundColor = foregroundColor5;
                    Console.BackgroundColor = backgroundColor3;
                    StringIsNotM8BQuestion  = true;
                }
                bool flag10 = text.ToLower() == "you suck!";
                if (flag10)
                {
                    break;
                    Console.WriteLine("Exit failed. Just know that you are disrespected.");
                    StringIsNotM8BQuestion = true;
                }
                bool flag11 = text == "...";
                if (flag11)
                {
                    speechSynthesizer.Speak("I'm tired of people who don't ask questions. Please do so or exit.");
                    Console.WriteLine("I'm tired of people who don't ask questions. Please do so or exit.");
                    StringIsNotM8BQuestion = true;
                }
                bool flag12 = text.Length == 0;
                if (flag12)
                {
                    speechSynthesizer.Speak("Ask a question, please.");
                    Console.WriteLine("Ask a question, please.");
                    StringIsNotM8BQuestion = true;
                }
                bool flag13 = text.ToLower() == "about";
                if (flag13)
                {
                    Program.About();
                    StringIsNotM8BQuestion = true;
                }
                bool flag14 = text.ToLower() == "quit";
                if (flag14)
                {
                    goto Block_13;
                }
                bool flag15 = text.ToLower() == "exit";
                if (flag15)
                {
                    goto Block_14;
                }
                if (StringIsNotM8BQuestion == false)
                {
                    switch (random.Next(4))
                    {
                    case 0:
                        Console.WriteLine("YES");
                        speechSynthesizer.Speak("Yes");
                        break;

                    case 1:
                        Console.WriteLine("NO");
                        speechSynthesizer.Speak("No");
                        break;

                    case 2:
                        Console.WriteLine("HELL NO");
                        speechSynthesizer.Speak("Hell no");
                        break;

                    case 3:
                        Console.WriteLine("HELL YES");
                        speechSynthesizer.Speak("Hell yes");
                        break;
                    }
                }
            }

            Console.WriteLine("According to the positions of the stars above, you are the human that sucks.");
            Console.ReadKey();
Block_13:
Block_14:
            Console.ForegroundColor = foregroundColor;
        }
예제 #56
0
파일: Profile.cs 프로젝트: iNgeon/AVPI
        public Profile(string filename)
        {
            try
            {
                Profile_Triggers        = new List <Trigger>();
                Profile_ActionSequences = new List <Action_Sequence>();
                ProfileDB = new Database();


                synth = new SpeechSynthesizer(); //used by action Speak

                if (filename != null)
                {
                    load_profile(filename);
                }
            }
            catch (Exception profile_err)
            {
                MessageBox.Show("Problem loading profile.\n" + profile_err.Message, "Error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
            }
            finally
            {
                /**/
            }
        }

        public void Add_Trigger(Trigger trigger_toAdd)
        {
            Profile_Triggers.Add(trigger_toAdd);
        }

        public void Add_Action_Sequence(Action_Sequence action_sequence_toAdd)
        {
            Profile_ActionSequences.Add(action_sequence_toAdd);
        }

        #region Trigger Validation Function
        public bool isTriggerValueTaken(string value_to_check)
        {
            // Predicate searches for the first match of value to value_to_check
            // it will return the object (trigger), if its not null then it must exist
            // you could also for loop through all triggers here, runtime O(n)
            if (Profile_Triggers.Find(trigger => trigger.value == value_to_check) != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }

        public bool isTriggerNameTaken(string name_to_check)
        {
            // Predicate searches for the first match of name to name_to_check
            // it will return the object (trigger), if its not null then it must exist
            // you could also for loop through all triggers here, runtime O(n)
            if (Profile_Triggers.Find(trigger => trigger.name == name_to_check) != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }

        #endregion

        #region Action Sequence Validation Functions
        public bool isActionSequenceNameTaken(string name_to_check)
        {
            if (Profile_ActionSequences.Find(aseq => aseq.name == name_to_check) != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }

        #endregion
        //
        //  public bool NewProfile()
        //
        //  Requesting a new Profile eliminates any existing Profile, and is therefore destructive.
        //
        //  Returns true if the new Profile was created of false if otherwise.
        //

        public bool NewProfile()
        {
            //  Instantiate a fresh Profile...

            Profile_Triggers        = new List <Trigger>();
            Profile_ActionSequences = new List <Action_Sequence>();

            //  And reset any states...

            UnsavedProfileChanges = false;
            ProfileFilename       = null;
            AssociatedProcess     = null;

            return(true);
        }  //  public bool NewProfile()

        public bool load_profile(string filename)
        {
            if (filename == null)
            {
                return(false);
            }

            //  Reset any states...

            NewProfile();

            XmlDocument profile_xml = new XmlDocument();

            //  Let's ensure that the user has actually selected a well-formed XML document for us to navigate as
            //  opposed to - oh, I don't know: a picture of their cat?

            try
            {
                profile_xml.Load(filename);
            }
            catch (Exception)
            {
                return(false);
            }

            //Check first element tag
            if (profile_xml.DocumentElement.Name != "gavpi")
            {
                throw new Exception("Malformed profile expected first tag gavpi got,"
                                    + profile_xml.DocumentElement.Name);
            }

            XmlNodeList profile_xml_elements = profile_xml.DocumentElement.ChildNodes;

            foreach (XmlNode element in profile_xml_elements)
            {
                if (element.Name == "AssociatedProcess")
                {
                    AssociatedProcess = element.InnerText;
                }
                // Load Action Sequences and their associated Actions.
                else if (element.Name.Contains("Action_Sequence"))
                {
                    Action_Sequence ack_frm_file = null;
                    try
                    {
                        ack_frm_file = new Action_Sequence(element, ProfileDB, this.synth);
                        // Check if the profile contains any sequences by this name.
                        if (!Profile_ActionSequences.Any(ack => ack.name == ack_frm_file.name))
                        {
                            Profile_ActionSequences.Add(ack_frm_file);
                        }
                        else
                        {
                            throw new ArgumentException("An action sequence with this name already exists.");
                        }
                    }
                    catch
                    {
                        // Log that we are discarding this malformed action sequence.
                    }
                }
                else if (element.Name.Contains("Trigger"))
                {
                    Trigger trig_frm_file;
                    string  trigger_name    = element.Attributes.GetNamedItem("name").Value;
                    string  trigger_type    = element.Attributes.GetNamedItem("type").Value;
                    string  trigger_value   = element.Attributes.GetNamedItem("value").Value;
                    string  trigger_comment = element.Attributes.GetNamedItem("comment").Value;

                    // Add backward compatability with older profiles.
                    if (trigger_type == "VI_Phrase")
                    {
                        trigger_type = "Phrase";
                    }

                    Type   new_trigger_type = Type.GetType("GAVPI." + trigger_type);
                    object trigger_isntance = trigger_isntance = Activator.CreateInstance(new_trigger_type, trigger_name, trigger_value);
                    trig_frm_file         = (Trigger)trigger_isntance;
                    trig_frm_file.comment = trigger_comment;

                    // Trigger Events
                    foreach (XmlElement trigger_event in element.ChildNodes)
                    {
                        string event_type  = trigger_event.Attributes.GetNamedItem("type").Value;
                        string event_name  = trigger_event.Attributes.GetNamedItem("name").Value;
                        string event_value = trigger_event.Attributes.GetNamedItem("value").Value;
                        if (event_type.Contains("Action_Sequence"))
                        {
                            trig_frm_file.Add(Profile_ActionSequences.Find(ackseq => ackseq.name == event_name));
                        }
                        else if (event_type.Contains("Phrase"))
                        {
                            Trigger newMetaTrigger;
                            Type    meta_trigger_type     = Type.GetType("GAVPI." + event_type);
                            object  meta_trigger_isntance = Activator.CreateInstance(meta_trigger_type, event_name, event_value);
                            newMetaTrigger = (Trigger)meta_trigger_isntance;

                            trig_frm_file.Add(newMetaTrigger);
                        }
                    }

                    // Malformed xml or double load, need to switch to dictionaries tbh
                    // agreed, but there are enough things to do atm 04.07.15
                    if (!Profile_Triggers.Any(trig => trig.name == trig_frm_file.name))
                    {
                        Profile_Triggers.Add(trig_frm_file);
                    }
                }
                else if (element.Name.Contains("Database") || element.Name.Contains("DB"))
                {
                    // Hand reader to DB
                    if (ProfileDB != null)
                    {
                        ProfileDB.load(element);
                    }
                }
                else
                {
                    /*
                     * throw new Exception("Malformed profile file, unexpected element "
                     + element.Name);
                     */
                }
            }
예제 #57
0
 public async Task Play(PlayType playType, TimeSpan duration, CancellationToken stopToken, CancellationToken restartToken)
 {
     if (!await _sync.WaitAsync(duration))
     {
         return;
     }
     try
     {
         Stopwatch.Restart();
         SoundPlayer       p  = null;
         SpeechSynthesizer ss = null;
         int count            = -1;
         while (Stopwatch.Elapsed < duration && !stopToken.IsCancellationRequested && !restartToken.IsCancellationRequested)
         {
             count++;
             if (playType == PlayType.Notify)
             {
                 if (p == null)
                 {
                     p = new SoundPlayer("Blip.wav");
                 }
                 if (count % 30 == 0)
                 {
                     p.Play();
                 }
                 await Task.Delay(500);
             }
             else if (playType == PlayType.Warn)
             {
                 if (p == null)
                 {
                     p = new SoundPlayer("Warn.wav");
                     p.PlayLooping();
                 }
                 if (count % 10 == 0)
                 {
                     if (ss == null)
                     {
                         ss = new SpeechSynthesizer();
                         ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Adult);
                         ss.Volume = 100;
                     }
                     ss?.SpeakAsync("Disable security system");
                 }
                 await Task.Delay(500);
             }
             else if (playType == PlayType.Alarm)
             {
                 if (p == null)
                 {
                     p = new SoundPlayer("PoliceSiren.wav");
                     p.PlayLooping();
                 }
                 await Task.Delay(500);
             }
         }
         p?.Stop();
         p?.Dispose();
         p = null;
         ss?.Pause();
         ss?.Dispose();
         ss = null;
         if (!restartToken.IsCancellationRequested && !stopToken.IsCancellationRequested)
         {
             CompletedTaskCompletionSource.TrySetResult(true);
         }
     }
     finally
     {
         _sync.Release();
     }
 }
        public void Speak(string script, string voice, int echoDelay, int distortionLevel, int chorusLevel, int reverbLevel, int compressLevel, bool radio)
        {
            if (script == null)
            {
                return;
            }

            try
            {
                using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    using (MemoryStream stream = new MemoryStream())
                    {
                        if (String.IsNullOrWhiteSpace(voice))
                        {
                            voice = configuration.StandardVoice;
                        }
                        if (voice != null)
                        {
                            try
                            {
                                synth.SelectVoice(voice);
                            }
                            catch { }
                        }

                        synth.Rate   = configuration.Rate;
                        synth.Volume = configuration.Volume;

                        synth.SetOutputToWaveStream(stream);
                        string speech = SpeechFromScript(script);
                        if (speech.Contains("<phoneme"))
                        {
                            speech = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" xml:lang=\"" + locale + "\"><s>" + speech + "</s></speak>";
                            synth.SpeakSsml(speech);
                        }
                        else
                        {
                            synth.Speak(speech);
                        }
                        stream.Seek(0, SeekOrigin.Begin);

                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(Environment.GetEnvironmentVariable("AppData") + @"\EDDI\speech.log", true)) { file.WriteLine("" + System.Threading.Thread.CurrentThread.ManagedThreadId + ": Turned script " + script + " in to speech " + speech); }

                        IWaveSource source = new WaveFileReader(stream);

                        // We need to extend the duration of the wave source if we have any effects going on
                        if (chorusLevel != 0 || reverbLevel != 0 || echoDelay != 0)
                        {
                            // Add a base of 500ms plus 10ms per effect level over 50
                            source = source.AppendSource(x => new ExtendedDurationWaveSource(x, 500 + Math.Max(0, (configuration.EffectsLevel - 50) * 10)));
                        }

                        // Add various effects...

                        // We always have chorus
                        if (chorusLevel != 0)
                        {
                            source = source.AppendSource(x => new DmoChorusEffect(x)
                            {
                                Depth = chorusLevel, WetDryMix = Math.Min(100, (int)(180 * ((decimal)configuration.EffectsLevel) / ((decimal)100))), Delay = 16, Frequency = 2, Feedback = 25
                            });
                        }

                        // We only have reverb and echo if we're not transmitting or receiving
                        if (!radio)
                        {
                            if (reverbLevel != 0)
                            {
                                // We tone down the reverb level with the distortion level, as the combination is nasty
                                source = source.AppendSource(x => new DmoWavesReverbEffect(x)
                                {
                                    ReverbTime = (int)(1 + 999 * ((decimal)configuration.EffectsLevel) / ((decimal)100)), ReverbMix = Math.Max(-96, -96 + (96 * reverbLevel / 100) - distortionLevel)
                                });
                            }

                            if (echoDelay != 0)
                            {
                                // We tone down the echo level with the distortion level, as the combination is nasty
                                source = source.AppendSource(x => new DmoEchoEffect(x)
                                {
                                    LeftDelay = echoDelay, RightDelay = echoDelay, WetDryMix = Math.Max(5, (int)(10 * ((decimal)configuration.EffectsLevel) / ((decimal)100)) - distortionLevel), Feedback = Math.Max(0, 10 - distortionLevel / 2)
                                });
                            }
                        }

                        if (configuration.EffectsLevel > 0 && distortionLevel > 0)
                        {
                            source = source.AppendSource(x => new DmoDistortionEffect(x)
                            {
                                Edge = distortionLevel, Gain = -6 - (distortionLevel / 2), PostEQBandwidth = 4000, PostEQCenterFrequency = 4000
                            });
                        }

                        if (radio)
                        {
                            source = source.AppendSource(x => new DmoDistortionEffect(x)
                            {
                                Edge = 7, Gain = -4 - distortionLevel / 2, PostEQBandwidth = 2000, PostEQCenterFrequency = 6000
                            });
                            source = source.AppendSource(x => new DmoCompressorEffect(x)
                            {
                                Attack = 1, Ratio = 3, Threshold = -10
                            });
                        }

                        EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                        var             soundOut   = new WasapiOut();
                        soundOut.Initialize(source);
                        soundOut.Stopped += (s, e) => waitHandle.Set();

                        activeSpeeches.Add(soundOut);
                        soundOut.Play();

                        // Add a timeout, in case it doesn't come back
                        waitHandle.WaitOne(source.GetTime(source.Length));

                        // It's possible that this has been disposed of, so ensure that it's still there before we try to finish it
                        lock (activeSpeeches)
                        {
                            if (activeSpeeches.Contains(soundOut))
                            {
                                activeSpeeches.Remove(soundOut);
                                soundOut.Stop();
                                soundOut.Dispose();
                            }
                        }

                        source.Dispose();
                    }
            }
            catch (Exception ex)
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(Environment.GetEnvironmentVariable("AppData") + @"\EDDI\speech.log", true)) { file.WriteLine("" + System.Threading.Thread.CurrentThread.ManagedThreadId + ": Caught exception " + ex); }
            }
        }
예제 #59
0
        // Speech synthesis events.
        public static async Task SynthesisEventsAsync()
        {
            // Creates an instance of a speech config with specified subscription key and service region.
            // Replace with your own subscription key and service region (e.g., "westus").
            var config = SpeechConfig.FromSubscription("YourSubscriptionKey", "YourServiceRegion");

            // Creates a speech synthesizer with a null output stream.
            // This means the audio output data will not be written to any stream.
            // You can just get the audio from the result.
            using (var synthesizer = new SpeechSynthesizer(config, null as AudioConfig))
            {
                // Subscribes to events
                synthesizer.SynthesisStarted += (s, e) =>
                {
                    Console.WriteLine("Synthesis started.");
                };

                synthesizer.Synthesizing += (s, e) =>
                {
                    Console.WriteLine($"Synthesizing event received with audio chunk of {e.Result.AudioData.Length} bytes.");
                };

                synthesizer.SynthesisCompleted += (s, e) =>
                {
                    Console.WriteLine("Synthesis completed.");
                };

                while (true)
                {
                    // Receives a text from console input and synthesize it to result.
                    Console.WriteLine("Enter some text that you want to synthesize, or enter empty text to exit.");
                    Console.Write("> ");
                    string text = Console.ReadLine();
                    if (string.IsNullOrEmpty(text))
                    {
                        break;
                    }

                    using (var result = await synthesizer.SpeakTextAsync(text))
                    {
                        if (result.Reason == ResultReason.SynthesizingAudioCompleted)
                        {
                            Console.WriteLine($"Speech synthesized for text [{text}].");
                            var audioData = result.AudioData;
                            Console.WriteLine($"{audioData.Length} bytes of audio data received for text [{text}]");
                        }
                        else if (result.Reason == ResultReason.Canceled)
                        {
                            var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
                            Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

                            if (cancellation.Reason == CancellationReason.Error)
                            {
                                Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
                                Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
                                Console.WriteLine($"CANCELED: Did you update the subscription info?");
                            }
                        }
                    }
                }
            }
        }
예제 #60
-2
        public void perform(IntPtr winPointer) {
            SetForegroundWindow(winPointer);
            ShowWindow(winPointer, 5);
            foreach (Actions a in actionList) {
                a.perform();
            }
            if (answering && answeringString != null) {
                try {
                    SpeechSynthesizer synth = new SpeechSynthesizer();
                    if (synth != null) {
                        synth.SpeakAsync(answeringString);
                    }
                }
                catch(Exception e){
                    
                }
            }

            if (answeringSound && answeringSoundPath != null) {
                if (answeringSoundPath.IndexOf(".wav") == answeringSoundPath.Length-4) {
                    System.Media.SoundPlayer player = new System.Media.SoundPlayer();
                    player.SoundLocation = answeringSoundPath;
                    player.Play();
                }
                else if (answeringSoundPath.IndexOf(".mp3") == answeringSoundPath.Length - 4) {
                    WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();

                    wplayer.URL = answeringSoundPath;
                    wplayer.controls.play();
                }
            }
        }