Exemple #1
1
 public void ShowAction(String text)
 {
     this.action.Dispatcher.BeginInvoke(
        (Action)(() =>
        {
            this.action.Text = text;
            PromptBuilder pb = new PromptBuilder();
            pb.AppendText(text + "!");
            synthesizer.Speak(pb);
        }
     ));
 }
        public PromptBuilder ToPromptBuilder(String defaultVoice)
        {
            PromptBuilder builder = new PromptBuilder(CultureUtil.GetOriginalCulture());
            builder.StartVoice(defaultVoice);

            var tags = GetTagsInText();

            int startIndex = 0;
            foreach (ITag tag in tags)
            {
                String textBeforeCurrentTag = _contents.Substring(startIndex, tag.Start - startIndex);
                builder.AppendText(textBeforeCurrentTag);

                bool isCommandSuccessful = tag.Apply(builder);
                if (isCommandSuccessful)
                {
                    startIndex = tag.End + 1;
                }
            }

            String remaining = _contents.Substring(startIndex).Trim();
            builder.AppendText(remaining);
            builder.EndVoice();
            return builder;
        }
        protected override void HandleNotification(Notification notification, string displayName)
        {
            StringBuilder sb = new StringBuilder();

            PromptBuilder pb = new PromptBuilder();
            pb.AppendText(notification.Title, PromptEmphasis.Strong);
            pb.AppendBreak();
            pb.AppendText(notification.Description);

            ss.Speak(pb);
        }
 public static void Test()
 {
     SpeechSynthesizer synth = new SpeechSynthesizer();
     PromptBuilder pb = new PromptBuilder();
     pb.AppendText("Welcome, everyone");
     synth.Speak(pb);
 }
 // Méthode permettant de lancer la synthese vocale asynchrone
 //
 public static void SpeechAsynchrone(String texte)
 {
     SpeechSynthesizer s = new SpeechSynthesizer();
     PromptBuilder builder = new PromptBuilder(new System.Globalization.CultureInfo("fr-fr"));
     builder.AppendText(texte);
     s.SpeakAsync(builder);
 }
 public void SpeechSynthesisTest()
 {
     var builder = new PromptBuilder();
     builder.AppendText("The build breaker is, dave.");
     var player = new AudioPlayer(new CradiatorSpeechSynthesizer(new SpeechSynthesizer()), new ConfigSettings(),
                                  new VoiceSelector(null), new AppLocation());
     player.Say(builder);
 }
        protected override void HandleNotification(Notification notification, string displayName)
        {
            /*
            string xml = @"<p>
                            <s>You have 4 new messages.</s>
                            <s>The first is from Stephanie Williams and arrived at <break/> 3:45pm.
                            </s>
                            <s>
                              The subject is <prosody rate=""-20%"">ski trip</prosody>
                            </s>
                          </p>";
             * */

            PromptBuilder pb = new PromptBuilder();

            // handle title
            if (notification.CustomTextAttributes != null && notification.CustomTextAttributes.ContainsKey("Notification-Title-SSML"))
                pb.AppendSsmlMarkup(notification.CustomTextAttributes["Notification-Title-SSML"]);
            else
                pb.AppendText(notification.Title, PromptEmphasis.Strong);

            pb.AppendBreak();

            // handle text
            if (notification.CustomTextAttributes != null && notification.CustomTextAttributes.ContainsKey("Notification-Text-SSML"))
                pb.AppendSsmlMarkup(notification.CustomTextAttributes["Notification-Text-SSML"]);
            else
                pb.AppendText(notification.Description);

            try
            {
                ss.Speak(pb);
            }
            catch (Exception ex)
            {
                Growl.CoreLibrary.DebugInfo.WriteLine("Unable to speak input: " + ex.Message);

                // fall back to plain text (if the plain text is what failed the first time, it wont work this time either but wont hurt anything)
                pb.ClearContent();
                pb.AppendText(notification.Title, PromptEmphasis.Strong);
                pb.AppendBreak();
                pb.AppendText(notification.Description);
                ss.Speak(pb);
            }
        }
Exemple #8
0
 public void initializeSpeech()
 {
     this.speaker.SetOutputToDefaultAudioDevice();
     PromptBuilder builder = new PromptBuilder();
     this.speaker.Volume = 100;
     this.speaker.Rate = 1;
     builder.AppendText("Jen, You are a re-de-culous Girl! And I love you");
     speaker.Speak(builder);
 }
 public void SpeakNow(string text)
 {
     var pBuilder = new PromptBuilder();
     pBuilder.ClearContent();
     pBuilder.AppendText(text + " is to be said as ");
     // pBuilder.AppendText(tvm.Translations.Last().Target);
     var speaker = new SpeechSynthesizer();
     speaker.Speak(pBuilder);
 }
Exemple #10
0
        private static void SynthToCam(string text, CameraWindow cw)
        {
            var synthFormat = new System.Speech.AudioFormat.SpeechAudioFormatInfo(System.Speech.AudioFormat.EncodingFormat.Pcm, 11025, 16, 1, 22100, 2, null);
            using (var synthesizer = new SpeechSynthesizer())
            {
                using (var waveStream = new MemoryStream())
                {

                    //write some silence to the stream to allow camera to initialise properly
                    var silence = new byte[1 * 22050];
                    waveStream.Write(silence, 0, silence.Length);

                    var pbuilder = new PromptBuilder();
                    var pStyle = new PromptStyle
                    {
                        Emphasis = PromptEmphasis.Strong,
                        Rate = PromptRate.Slow,
                        Volume = PromptVolume.ExtraLoud
                    };

                    pbuilder.StartStyle(pStyle);
                    pbuilder.StartParagraph();
                    pbuilder.StartVoice(VoiceGender.Male, VoiceAge.Adult, 2);
                    pbuilder.StartSentence();
                    pbuilder.AppendText(text);
                    pbuilder.EndSentence();
                    pbuilder.EndVoice();
                    pbuilder.EndParagraph();
                    pbuilder.EndStyle();

                    synthesizer.SetOutputToAudioStream(waveStream, synthFormat);
                    synthesizer.Speak(pbuilder);
                    synthesizer.SetOutputToNull();

                    //write some silence to the stream to allow camera to end properly
                    waveStream.Write(silence, 0, silence.Length);
                    waveStream.Seek(0, SeekOrigin.Begin);

                    var ds = new DirectStream(waveStream) { RecordingFormat = new WaveFormat(11025, 16, 1) };
                    var talkTarget = TalkHelper.GetTalkTarget(cw.Camobject, ds); 
                    ds.Start();
                    talkTarget.Start();
                    while (ds.IsRunning)
                    {
                        Thread.Sleep(100);
                    }
                    ds.Stop();
                    talkTarget.Stop();
                    talkTarget = null;
                    ds = null;
                }
            }


        }
 private void cmdPromptTest_Click(object sender, RoutedEventArgs e)
 {
     PromptBuilder prompt = new PromptBuilder();
     
     prompt.AppendText("How are you");            
     prompt.AppendBreak(TimeSpan.FromSeconds(2));
     prompt.AppendText("How ", PromptEmphasis.Reduced);
     PromptStyle style = new PromptStyle();
     style.Rate = PromptRate.ExtraSlow;
     style.Emphasis = PromptEmphasis.Strong;
     prompt.StartStyle(style);
     prompt.AppendText("are ");
     prompt.EndStyle();            
     prompt.AppendText("you?");          
     
     
     
     SpeechSynthesizer synthesizer = new SpeechSynthesizer();
     synthesizer.Speak(prompt);
     
 }
Exemple #12
0
        void recEngine_SpeachSpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            switch (e.Result.Text)
            {
                case "say hello":
                    //MessageBox.Show("Hello Denis. How are you?"); break;

                    PromptBuilder promtBuilder = new PromptBuilder();
                    promtBuilder.StartSentence();
                    promtBuilder.AppendText("Hello Denis");
                    promtBuilder.EndSentence();

                    promtBuilder.AppendBreak(PromptBreak.ExtraSmall);
                    promtBuilder.AppendText("How are you?");

                    syncSpeechSynthesizer.SpeakAsync("Hello Denis. How are you?"); break;
                case "print my name":
                    richTextBox1.Text += "\nDenis"; break;
                case "speak selected text":
                    syncSpeechSynthesizer.SpeakAsync(richTextBox1.SelectedText); break;
            }
        }
Exemple #13
0
        public void SpeakWithPromptBuilder() {
            var builder = new PromptBuilder();
            builder.AppendText("This is something of a test");
            builder.AppendAudio(@"E:\OneDrive\Music\mycomp\MusicalIntervals01\ExtractedPianoNotes\F#5.wav");
            builder.AppendAudio(@"E:\OneDrive\Music\mycomp\MusicalIntervals01\ExtractedPianoNotes\E5.wav");

            builder.AppendAudio(@"E:\OneDrive\Music\mycomp\MusicalIntervals01\ExtractedPianoNotes\PerfectFourth2.wav" );
            builder.AppendAudio(@"E:\OneDrive\Music\mycomp\MusicalIntervals01\ExtractedPianoNotes\PerfectFourth3.wav");


            _speechSynthesizer.Speak(builder);

        }
Exemple #14
0
        PromptBuilder MakeSpeech(IEnumerable<ProjectStatus> projects, string rawSentence)
        {
            var promptBuilder = new PromptBuilder();

            if (string.IsNullOrEmpty(rawSentence)) return promptBuilder;

            promptBuilder.AppendBreak(OneSecond);
            foreach (var project in projects)
            {
                promptBuilder.AppendBreak(OneSecond);
                promptBuilder.AppendText(_speechTextParser.Parse(rawSentence, project));
            }
            return promptBuilder;
        }
Exemple #15
0
        public static void say(String tts)
        {
            Console.WriteLine("[TTS] Say: {0}", tts);
            using (SpeechSynthesizer synthesizer = new SpeechSynthesizer()) {

                // Configure the audio output.
                synthesizer.SetOutputToDefaultAudioDevice();

                // Build and speak a prompt.
                PromptBuilder builder = new PromptBuilder();
                builder.AppendText(tts);
                synthesizer.Speak(builder);
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            if( args.Length != 1)
            {
                Console.WriteLine("Usage: CreateWavFiles.exe file.csv" );
                return;
            }

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

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

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

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

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

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

            Console.WriteLine();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    public void Speak(String tts, bool sync) {
      Log("Speaking: " + tts);
      try {
        PromptBuilder builder = new PromptBuilder();
        builder.Culture = new CultureInfo(ConfigManager.GetInstance().Find("bot.language", "fr-FR"));
        builder.AppendText(tts);
        
        using (var ms = new MemoryStream()) {
          lock (synthesizer) {
            synthesizer.SetOutputToWaveStream(ms);
            synthesizer.Speak(builder);
          }
          ms.Position = 0;
          if (ms.Length <= 0) { return; }

          AddOnManager.GetInstance().AfterHandleVoice(tts, sync, ms);
        }
      }
      catch (Exception ex) {
        Error(ex);
      }
    }
Exemple #18
0
        private void newEx()

        {
            trueShoot         = wrongShoot = 0;
            timer1.Enabled    = true;
            gameTimer.Enabled = true;
            timer1.Start();
            lettre      = lettres[r.Next(0, 7)].ToLower();
            childThread = new Thread(new ThreadStart(() =>
            {
                sSynth = new SpeechSynthesizer();
                PromptBuilder pBuilder             = new PromptBuilder();
                SpeechRecognitionEngine sRecognize = new SpeechRecognitionEngine(new CultureInfo("fr-FR"));
                //int i = 0;
                //  PictureBox[] soundPhrases = { soundPhrase1, soundPhrase2, soundPhrase3, soundPhrase4 };
                //  while (soundPhrases[i].Name != pBoxName) { i++; }
                //pbox = soundPhrases[i];
                pBuilder.ClearContent();
                string s = "tirer tous les mots contenants la lettre" + lettre;
                pBuilder.AppendText(s);
                sSynth.Speak(pBuilder);
                sSynth.Dispose();
            }));

            childThread.Start();



            //try { sSynth.Pause(); }catch (Exception) { };


            lettreLabel.Text = "tirer tous les mots contenants la lettre " + lettre;
            string allWords = SearchFrs.allWords();

            string[] t = allWords.Split(',');

            Label[] labels = { label1, label2, label3, label4, label5, label6 };

            int i = 0; j = r.Next(1, 5);

            List <string> mots = new List <string>();
            int           lettreMotCount = 0, nonLettreCount = 0, k = 0;


            while ((i < allWords.Length) && (k < 6))
            {
                if ((t[i].IndexOf(lettre) == -1) && (nonLettreCount < 6 - j))
                {
                    mots.Add(t[i]); k++; nonLettreCount++;
                }
                else
                {
                    if ((t[i].IndexOf(lettre) != -1) && (lettreMotCount < j))
                    {
                        mots.Add(t[i]); k++; lettreMotCount++;
                    }
                }
                i++;
            }


            k = 0; int x = 26;
            while (k < 6)
            {
                i = r.Next(0, mots.Count); labels[k].Show();
                labels[k].Text     = mots[i]; labels[k].Tag = "invaders";
                labels[k].Location = new Point(x, 55); x = x + 120;
                mots.RemoveAt(i);
                k++;
            }
        }
Exemple #19
0
        /// <summary>
        /// Sends the string to the speech syncth to speak
        /// async. Returns a bookmark. When the bookmark is
        /// reached, an event raised.
        /// </summary>
        /// <param name="text">String to convert</param>
        /// <param name="bookmark">returns bookmark</param>
        /// <returns>true on success</returns>
        public bool SpeakAsync(String text, out int bookmark)
        {
            bool retVal = true;

            bookmark = _nextBookmark++;
            try
            {
                if (!IsMuted())
                {
                    var promptBuilder = new PromptBuilder();
                    promptBuilder.AppendText(replaceWithAltPronunciations(text));
                    promptBuilder.AppendBookmark(bookmark.ToString());

                    Synthesizer.SpeakAsync(promptBuilder);
                }
            }
            catch (Exception ex)
            {
                Log.Debug(ex.ToString());
                retVal = false;
            }

            return retVal;
        }
Exemple #20
0
        public void Speak(string message, int speed = 0)
        {
            try
            {
                // Build a prompt.
                PromptBuilder builder = new PromptBuilder();
                builder.AppendText(message);

                // Synth message
                ss.Rate = speed;
                if (UseSSML)
                {
                    string ssmlString = "<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\"";

                    switch (lang)
                    {
                        case Language.English: ssmlString += " xml:lang=\"en-GB\">"; break;
                        case Language.Finish: ssmlString += " xml:lang=\"fi-FI\">"; break;
                        case Language.Norwegian: ssmlString += " xml:lang=\"nb-NO\">"; break;
                        case Language.Russian: ssmlString += " xml:lang=\"ru-RU\">"; break;
                        case Language.Swedish: ssmlString += " xml:lang=\"sv-SE\">"; break;
                        default: ssmlString += " xml:lang=\"en-GB\">"; break;
                    }

                    ssmlString += "<s>" + message + "</s></speak>";

                    if (AsyncMode) ss.SpeakSsmlAsync(ssmlString);
                    else ss.SpeakSsml(ssmlString);
                }
                else
                {
                    if (AsyncMode) ss.SpeakAsync(builder);
                    else ss.Speak(builder);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occured: '{0}'", e);
            }
        }
Exemple #21
0
        private static void HasTask(TrainSeat train, string data, Seat seat)
        {
            if (ShowMessage != null)
            {
                ShowMessage(null, new List<Message>() { new Message(string.Format("{0},{1},{2}有票", train.ToString(), data, seat.Name), Color.Yellow) });

                MessageBox.Show(Program.mainForm, "有票啦。。。。" + seat.Name);

                ThreadPool.QueueUserWorkItem((m) =>
                {
                    SpeechSynthesizer synthesizer = new SpeechSynthesizer();

                    PromptBuilder promptBuilder = new PromptBuilder();

                    promptBuilder.AppendText("买到票啦,我能回家啦!");

                    synthesizer.SpeakAsync(promptBuilder);

                });
            }
        }
        private static void WriteLine(string input)
        {
            Console.WriteLine(input);
            
            var prompt = new PromptBuilder();
            //build a prompt with a specific string to translate to speech
            //note there's a bunch of overloads to control the volume, rate
            //and other speech factors
            prompt.AppendText(input);

            speech.Speak(prompt);
        }
Exemple #23
0
        private void btnCreateWAVAdd_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(tbText.Text) && !string.IsNullOrWhiteSpace(tbKeys.Text) && !string.IsNullOrWhiteSpace(tbWhereSave.Text) && Directory.Exists(tbWhereSave.Text))
            {
                Keys[] convertedKeys;
                string error;

                if (Helper.keysArrayFromString(tbKeys.Text, out convertedKeys, out error))
                {
                    if (convertedKeys.Length > 0)
                    {
                        var newKS = new XMLSettings.KeysSounds(convertedKeys, new string[] { tbWhereSave.Text + "\\" + Helper.cleanFileName(tbText.Text.Replace(" ", "") + ".wav") });

                        synth = new SpeechSynthesizer();
                        synth.SetOutputToWaveFile(newKS.SoundLocations[0]);

                        PromptBuilder builder = new PromptBuilder();
                        builder.AppendText(tbText.Text);

                        synth.Speak(builder);

                        synth.Dispose();
                        synth = null;

                        mainForm.keysSounds.Add(newKS);

                        var newItem = new ListViewItem(tbKeys.Text);
                        newItem.SubItems.Add(newKS.SoundLocations[0]);

                        mainForm.lvKeySounds.Items.Add(newItem);

                        mainForm.lvKeySounds.ListViewItemSorter = new ListViewItemComparer(0);
                        mainForm.lvKeySounds.Sort();

                        mainForm.keysSounds.Sort(delegate(XMLSettings.KeysSounds x, XMLSettings.KeysSounds y)
                        {
                            if (x.Keys == null && y.Keys == null)
                            {
                                return(0);
                            }
                            else if (x.Keys == null)
                            {
                                return(-1);
                            }
                            else if (y.Keys == null)
                            {
                                return(1);
                            }
                            else
                            {
                                return(Helper.keysToString(x.Keys).CompareTo(Helper.keysToString(y.Keys)));
                            }
                        });

                        MessageBox.Show("File saved to " + newKS.SoundLocations[0]);
                    }
                }
                else
                {
                    MessageBox.Show("Keys string incorrectly made. Check for spelling errors");
                }
            }
            else
            {
                MessageBox.Show("No text in text box, keys box, and/or where to save box... or the where to save folder does not exist");
            }
        }
Exemple #24
0
        public static void Poster()
        {
posthead:
            Random r = new Random(Guid.NewGuid().GetHashCode());

            try
            {
                if (Event_GroupMessage.ProtectCount >= 3)
                {
                    Log($"trapped in bug:{ReportBUGTime},{GetTickCount()}");
                    if (ReportBUGTime > 0)
                    {
                        if (GetTickCount() >= ReportBUGTime)
                        {
                            Log($"Unlimited network:{Event_GroupMessage.ProtectCount}/ ms", ConsoleColor.Red);
                            ReportBUGTime = 0;
                            string bugr = $"{DateTime.Now.ToString()}\n" +
                                          "机器人在处理消息时发现消息流量异常,可能机器人进程被长时间挂起。" +
                                          "为了避免机器人继续处理消息导致暴走,已经切断消息处理。" +
                                          "请持有32766级别以上权限的用户发送.bugclose解除切断。" +
                                          $"\n异常消息流量:{Event_GroupMessage.ProtectCount}条/毫秒\n\n若无人协助,则切断将在{Event_GroupMessage.ProtectCount * 10}秒后解除。";
                            new QQ(pCQ, 1361778219).SendPrivateMessage(bugr);
                            List <GroupInfo> gi = pCQ.GetGroupList();
                            foreach (GroupInfo gii in gi)
                            {
                                //gii.Group.SendGroupMessage(bugr);
                            }
                        }
                    }
                    Event_GroupMessage.ProtectCount--;
                    Thread.Sleep(10000);
                    goto posthead;
                }

                if (r.Next(0, 1000) == 88)
                {
                    if (DateTime.Now.Hour >= 7 && DateTime.Now.Hour < 24)
                    {
                        List <GroupInfo> lg = pCQ.GetGroupList();
                        Event_GroupMessage.Artifical(lg[r.Next(0, lg.Count)].Group);
                    }
                }

                //OSU
                if (LastOSUTime == DateTime.Now.Hour && DateTime.Now.Minute == 30)
                {
                    Storage ignore = new Storage("ignore");
                    if (ignore.getkey("577344771", "artist") == "√")
                    {
                        goto NoPOSU;
                    }
                    LastOSUTime = (DateTime.Now.Hour + 1) % 24;
                    Group droid = new Group(pCQ, 577344771);
                    List <GroupMemberInfo> gml = droid.GetGroupMemberList();
                    GroupMemberInfo        gmi = gml[r.Next(0, gml.Count)];
                    long   qq      = gmi.QQ.Id;
                    string targett = MessagePoster.ptList[r.Next(0, MessagePoster.ptList.Count)];
                    ScriptDrawer.Draw("C:\\DataArrange\\PTemple\\" + targett + ".txt",
                                      MessagePoster.workpath + "\\data\\image\\" + targett + ".png",
                                      "[qq]", qq.ToString(),
                                      "[nick]", gmi.Nick,
                                      "[card]", gmi.Card == "" ? gmi.Nick : gmi.Card,
                                      "[sex]", gmi.Sex.ToString(),
                                      "[age]", gmi.Age.ToString(),
                                      "[group]", "577344771"
                                      );
                    droid.SendGroupMessage("现在是 " + DateTime.Now.Hour +
                                           "时30分 不整,恭喜幸运小朋友:" + CQApi.CQCode_At(qq) + "\n"
                                           + CQApi.CQCode_Image(targett + ".png"));
                }
NoPOSU:

                //BlackDied
                if (DateTime.Now.Hour == 24 || DateTime.Now.Hour == 0)
                {
                    if (DateTime.Now.Month == 3 && DateTime.Now.Day == 27)
                    {
                        if (!HasSendDie)
                        {
                            List <GroupInfo> gi = pCQ.GetGroupList();
                            foreach (GroupInfo gii in gi)
                            {
                                gii.Group.SendGroupMessage("今天。是黑嘴去世" + (DateTime.Now.Year - 2015) + "周年的日子。在这里打扰了大家,非常抱歉。\n黑嘴,名字来源于本机作者的一只狗,这只狗在本机作者的精神支柱上有很大的作用【虽然这听起来很荒唐】,它也渐渐在本机主人的脑子里逐渐扭曲抽象成了一种精神依靠。\n祝你在天堂快乐,黑嘴。       -3.27\n不接受任何对此条消息的议论。");
                            }
                            HasSendDie = true;
                        }
                    }
                }

                //Moring Protection
                Storage sys = new Storage("system");
                if (DateTime.Now.Hour >= 3 && DateTime.Now.Hour <= 5)
                {
                    if (sys.getkey("root", "sleep") != "zzz")
                    {
                        sys.putkey("root", "sleep", "zzz");
                        QQ master = new QQ(pCQ, 1361778219);
                        master.SendPrivateMessage("主人晚安~");
                        Console.Clear();
                        Log("[SLEEP] zzzzzzz");
                        logid = Guid.NewGuid().ToString();
                        //Application.Restart();
                        //System.Diagnostics.Process.Start(workpath + "\\CQA.exe", "/account 3529296290");
                        //System.Environment.Exit(0);
                    }
                    Thread.Sleep(1000);
                    goto posthead;
                }
                if (sys.getkey("root", "sleep") == "zzz")
                {
                    Log("[WAKE UP] ouch");
                    QQ master = new QQ(pCQ, 1361778219);
                    master.SendPrivateMessage("主人早上好~");
                    sys.putkey("root", "sleep", "!!");
                }

                Group g;
                //Say
                try
                {
                    for (int i = 0; i < delays.Count; i++)
                    {
resay:
                        delaymsg dm = delays[i];
                        if (GetTickCount() >= dm.time)
                        {
                            if (dm.voice == true)
                            {
                                SpeechSynthesizer reader = new SpeechSynthesizer();
                                string            fname  = GetTickCount().ToString();
                                reader.SetOutputToWaveFile(
                                    workpath + "\\data\\record\\say_" + fname + ".wav",
                                    new SpeechAudioFormatInfo(32000, AudioBitsPerSample.Sixteen, AudioChannel.Mono)
                                    );
                                reader.Rate   = -2 + new Random(Guid.NewGuid().GetHashCode()).Next(0, 4);
                                reader.Volume = 100;
                                //reader.SelectVoice("Microsoft Lili");
                                PromptBuilder builder = new PromptBuilder();
                                builder.AppendText(dm.msg);
                                Log("Speak started at :" + GetTickCount());
                                reader.Speak(builder);
                                Log("Speak successfully :" + GetTickCount());
                                reader.Dispose();
                                if (dm.kind == 0)
                                {
                                    new Group(pCQ, dm.group).SendGroupMessage(CQApi.CQCode_Record("say_" + fname + ".wav"));
                                }
                                else
                                {
                                    new QQ(pCQ, dm.group).SendPrivateMessage(CQApi.CQCode_Record("say_" + fname + ".wav"));
                                }
                            }
                            else
                            {
                                Log("Send successfully.");
                                if (dm.kind == 0)
                                {
                                    new Group(pCQ, dm.group).SendGroupMessage(dm.msg);
                                }
                                else
                                {
                                    new QQ(pCQ, dm.group).SendPrivateMessage(dm.msg);
                                }
                            }
                            delays.Remove(dm); goto resay;
                        }
                    }
                }
                catch
                {
                }

                //Undertale
                if (UT.targetg != 0)
                {
                    if (GetTickCount() - UT.tick >= 20000)
                    {
                        g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, UT.targetg);
                        if (UT.winstr == "")
                        {
                            g.SendGroupMessage("nobody passed round" + UT.round + ",answer:" + UT.role);
                        }
                        else
                        {
                            g.SendGroupMessage("answer:" + UT.role + "\n" + UT.winstr);
                        }

                        if (UT.round == 5)
                        {
                            string playstr = "";
                            for (int i = 0; i < UT.ps.Count; i++)
                            {
                                playstr = playstr + CQApi.CQCode_At(UT.ps[i].qq) + " " + (int)(UT.ps[i].score * 10) / 10 + " points\n";
                            }
                            UT.targetg = 0;
                            g.SendGroupMessage("game closed\n" + playstr);
                        }
                        else
                        {
                            UT.nextRound(); UT.tick = GetTickCount();
                            g.SendGroupMessage("round " + UT.round + "(result:20s later):" + UT.dialog);
                        }
                    }
                }

                //Hot Poster
                string fstr = ""; string estr = ""; string[] qtemp;
                HotMsg hhmsg = new HotMsg();
                for (int s = 0; s < Manager.mHot.data.Count; s++)
                {
                    hhmsg = (HotMsg)Manager.mHot.data[s];
                    if (DateTime.Now.Hour >= 22 && hhmsg.hasup == false && TenClockLock == false)
                    {
                        TenClockLock = true;
                        Log("Annouce:" + hhmsg.group, ConsoleColor.Green);
                        qtemp = hhmsg.banqq.Split(';');
                        for (int i = 0; i < qtemp.Length - 1; i++)
                        {
                            estr = estr + CQApi.CQCode_At(Convert.ToInt64(qtemp[i]));
                        }
                        qtemp = hhmsg.qq.Split(';');
                        for (int i = 0; i < qtemp.Length - 1; i++)
                        {
                            fstr = fstr + CQApi.CQCode_At(Convert.ToInt64(qtemp[i]));
                        }
                        hhmsg.hasup = true;
                        g           = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, Convert.ToInt64(hhmsg.group));
                        g.SendGroupMessage(hhmsg.msg);
                        Manager.mHot.data[s] = hhmsg;
                    }
                }
                //Homework network
                string f = "0";
                if (File.Exists("C:\\DataArrange\\homeworklock.bin"))
                {
                    f = File.ReadAllText("C:\\DataArrange\\homeworklock.bin", Encoding.UTF8);
                }
                if (Convert.ToInt64(f) == 1)
                {
                    Log("New homework recevied !", ConsoleColor.Green);
                    f = File.ReadAllText("C:\\DataArrange\\homework.bin", Encoding.UTF8);
                    g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, 817755769);
                    g.SendGroupMessage("[今日作业推送消息]\n" + f + "\n————来自黑嘴稽气人的自动推送");
                    File.WriteAllText("C:\\DataArrange\\homeworklock.bin", "0");
                }
                f = "";
                if (File.Exists("C:\\DataArrange\\announcer.bin"))
                {
                    f = File.ReadAllText("C:\\DataArrange\\announcer.bin", Encoding.UTF8);
                }
                if (f != "")
                {
                    Log("Announce:" + f, ConsoleColor.Green);
                    string[] p = f.Split('\\'); long gr = 0;
                    if (p[0] == "class")
                    {
                        gr = 817755769;
                    }
                    if (p[0] == "inter")
                    {
                        gr = 554272507;
                    }
                    g = new Native.Csharp.Sdk.Cqp.Model.Group(pCQ, gr);
                    switch (p[1])
                    {
                    case ("hlesson"):
                        f = "今天上午的网课出炉啦~\n地址:{url}\n往期网课精彩回顾:https://space.bilibili.com/313086171/channel/detail?cid=103565 ".Replace("{url}", p[2]);
                        break;

                    case ("lesson"):
                        f = "今天全天的网课出炉啦~\n地址:{url}\n往期网课精彩回顾:https://space.bilibili.com/313086171/channel/detail?cid=103565 ".Replace("{url}", p[2]);
                        break;

                    case ("default"):
                        f = p[2];
                        break;

                    default:
                        Log("Unkown announce .", ConsoleColor.Red);
                        return;
                    }
                    g.SendGroupMessage("[通知]\n" + f + "\n————来自黑嘴稽气人的自动推送");
                    File.WriteAllText("C:\\DataArrange\\announcer.bin", "");
                }
            }
            catch (Exception err)
            {
                Log(err.StackTrace + "\n" + err.Message, ConsoleColor.Red);
            }
            Thread.Sleep(1000);
            goto posthead;
        }
        /// <summary>
        /// This function reads an excerpt of MathML from "LISTBOX_ShowExcerpts".
        /// </summary>
        /// <param name="excerpt">The ID of the MathML excerpt to read</param>
        /// <param name="goDeeper">True to read ID tags recursively, false to read ID tags woodenly</param>
        /// <returns>A PromptBuilder representing a spoken rendering of the specified math excerpt</returns>
        private PromptBuilder ReadText( int excerpt, bool goDeeper )
        {
            PromptBuilder p = new PromptBuilder();

            string excerptAndPrompt = LISTBOX_ShowExcerpts.Items[ excerpt ].ToString();
            string excerptTag = GetXmlWrapper( excerptAndPrompt );
            //excerptTag = excerptTag.Substring( 6 );

            string tx = RetrieveExcerptFromListbox( excerptAndPrompt );

            Char[] c = tx.ToCharArray();

            bool speakMiChar = true;

            // These checks will determine if extra words are needed to delineate that we are in a
            //   special mathML tag
            bool spokeTag = false;
            string textExcerpt = "";

            for( int j = 1; j < ( MasterToken._elemCount ); j++ ) {
                Token t = MasterToken._mathMLelement[ j ];
                if( excerptTag == t._symbol ) {
                    p.AppendText( t._speech );
                    spokeTag = true;
                }
                if( t._symbol == "mtext" )
                    textExcerpt = MasterToken._elemEnglish[ j ][ 0 ];
            } // Check the mo group

            if( !spokeTag )
                p.AppendText( excerptTag );

            p.AppendBreak( new TimeSpan( 0, 0, 0, 0, 250 ) );

            // Check for Text tag; should be read literally
            if( ( excerptTag == "mtext" ) | ( excerptTag == textExcerpt ) ) {
                p.AppendText( tx );
                return p;
            }

            // This function will convert the text in the Textbox to speech
            for( int i = 0; i < ( tx.Length ); i++ ) {
                // Letters convert to an <m:mi> tag
                if( Char.IsLetter( c[ i ] ) & ( Convert.ToInt32( c[ i ] ) < 256 ) ) {			// Greek letters are considered letters!
                    // First, check if this letter begins a function name!
                    speakMiChar = true;

                    for( int j = 0; j < ( MasterToken._miCount ); j++ ) {
                        Token t = MasterToken._mi[ j ] as Token;
                        string sym = t._symbol;

                        if( sym.Length <= ( tx.Length - i ) ) {
                            if( tx.Substring( i, sym.Length ) == sym ) {
                                p.AppendText( t._speech + " " );
                                i = i + sym.Length - 1;
                                speakMiChar = false;
                                break;
                            }
                        }
                    } // Check the mi group

                    if( speakMiChar )
                        p.AppendTextWithHint( Convert.ToString( c[ i ] ) + " ", SayAs.SpellOut );
                } // Letter check

                if( Char.IsDigit( c[ i ] ) || c[ i ] == '.' ) {
                    int startNum = i;
                    int finNum = i;

                    for( finNum = i; finNum < tx.Length; finNum++ )
                        if( !Char.IsDigit( c[ finNum ] ) && c[ finNum ] != '.' && c[ finNum ] != ',' )
                            break;

                    string sayNum = "";

                    for( int k = i; k < finNum; k++ )
                        sayNum += c[ k ];

                    sayNum = Convert.ToDouble( sayNum ).ToString();
                    p.AppendTextWithHint( sayNum + " ", SayAs.Text );

                    i = finNum - 1;
                } // check for Numbers

                if( i < tx.Length ) {

                    // Otherwise, must find the speech text in the Master Token List XML
                    int j = 0;
                    for( j = 0; j < ( MasterToken._moCount ); j++ ) {
                        Token t = MasterToken._mo[ j ] as Token;
                        Char[] sym = t._symbol.ToCharArray();
                        if( c[ i ] == sym[ 0 ] )
                            p.AppendText( t._speech + " " );
                    } // Check the mo group

                    if( speakMiChar ) {
                        for( j = 0; j < ( MasterToken._miCount ); j++ ) {
                            Token t = MasterToken._mi[ j ] as Token;
                            string sym = t._symbol;
                            if( ( i + sym.Length ) < tx.Length )
                                if( tx.Substring( i, sym.Length ) == sym )
                                    p.AppendText( t._speech + " " );
                        } // Check the mi group
                    }

                    // ⊰- Finally, we need to test for Excerpt tags!
                    if( c[ i ] == '⊰' ) {
                        int thisID = Convert.ToInt32( tx.Substring( i + 1, 3 ) );

                        if( goDeeper == true ) {
                            PromptBuilder appendThis = new PromptBuilder();
                            appendThis = ReadText( thisID, true );
                            p.AppendPromptBuilder( appendThis );
                        }
                        else {
                            p.AppendText( "Line " );
                            p.AppendText( thisID.ToString() + " " );
                        }
                        i = i + 4;

                    } // Check for excerpt tags // -⊱

                    p.AppendBreak( new TimeSpan( 0, 0, 0, 0, 125 ) );
                }

            }

            return p;
        }
        /// <summary>
        /// This function is used to read a radical.
        /// </summary>
        /// <param name="node">The node that represents the radical portion of a "mroot" MathML element</param>
        /// <returns>Could be "square", "cube", "n-th", or "x"</returns>
        private PromptBuilder ReadRadical( System.Xml.XmlNode node )
        {
            PromptBuilder p = new PromptBuilder();
            TimeSpan shortPause = new TimeSpan( 0, 0, 0, 0, 50 );

            if( ( node.ChildNodes.Count == 1 ) && ( node.ChildNodes[ 0 ].Name == "mn" ) ) {
                if( node.ChildNodes[ 0 ].InnerText == "2" ) {
                    // Squared
                    p.AppendText( " squared " );
                }
                else if( node.ChildNodes[ 0 ].InnerText == "3" ) {
                    // Cubed
                    p.AppendText( " cube " );
                }
                else if( node.ChildNodes[ 0 ].InnerText.Contains( '.' ) ) {
                    // Contains a decimal... just read it
                    p.AppendPromptBuilder( ReadNode( node ) );
                }
                else {
                    // to the n-th power

                    string wordToRead = AddNumericalSuffix( node.ChildNodes[ 0 ].InnerText );

                    p.AppendText( wordToRead );
                }
            }
            else {
                // If not a simple number, simply read the node
                p.AppendPromptBuilder( ReadNode( node ) );
            }

            return p;
        }
Exemple #27
0
        public bool Speak(String tts)
        {
            if (tts == null) { return false; }

              WSRConfig.GetInstance().logInfo("TTS", "Say: " + tts);
              speaking = true;

              // Build and speak a prompt.
              PromptBuilder builder = new PromptBuilder();
              builder.AppendText(tts);
              synthesizer.SpeakAsync(builder);

              return true;
        }
 private void SuccessfullyLoggedSpeech()
 {
     PromptBuilder prompt = new PromptBuilder();
     prompt.AppendText("Hi", PromptRate.Slow );
     prompt.AppendText(WellcomeTextbox.Text,  PromptVolume.Loud );
     prompt.AppendText("Wellcome", PromptRate.Slow);
     SpeechSynthesizer synthesizer = new SpeechSynthesizer();
     synthesizer.SpeakAsync(prompt);
 }
 private void button1_Click(object sender, EventArgs e)
 {
     pBuilder.ClearContent();
     pBuilder.AppendText(textBox1.Text);
     sSynth.Speak(pBuilder);
 }
Exemple #30
0
    public void Speak(String tts) {

      if (tts == null) { return; }
      if (speaking) { return; } speaking = true;

      WSRConfig.GetInstance().logInfo("TTS", "[" + device + "] " + "Say: " + tts);
      try {
        // Build and speak a prompt.
        PromptBuilder builder = new PromptBuilder();
        builder.AppendText(tts);

        // Setup buffer
        using (var ms = new MemoryStream()) {
          synthesizer.SetOutputToWaveStream(ms);
          synthesizer.Speak(builder); // Synchronous
          ms.Position = 0;
          if (ms.Length > 0) {
            RunSession(WaveOutSpeech, new WaveFileReader(ms), "TTS");
          }
        }
      }
      catch (Exception ex) {
        WSRConfig.GetInstance().logError("TTS", ex);
      }

      WSRConfig.GetInstance().logInfo("PLAYER", "[" + device + "]" + "speaking false");
      speaking = false;
    }
Exemple #31
0
        // Play some dummy audio especially to keep audio link
        // to wireless device open, so user can play with mute sync function
        private void SimulatePhoneAudio()
        {
            // build and speak a prompt
            PromptBuilder builder = new PromptBuilder();
            #region Dummy Phone Text
            builder.AppendText(
                @"And sails upon the bosom of the air.

            JULIET

            O Romeo, Romeo! wherefore art thou Romeo?
            Deny thy father and refuse thy name;
            Or, if thou wilt not, be but sworn my love,
            And I'll no longer be a Capulet.

            ROMEO

            [Aside] Shall I hear more, or shall I speak at this?

            JULIET

            'Tis but thy name that is my enemy;
            Thou art thyself, though not a Montague.
            What's Montague? it is nor hand, nor foot,
            Nor arm, nor face, nor any other part
            Belonging to a man. O, be some other name!
            What's in a name? that which we call a rose
            By any other name would smell as sweet;
            So Romeo would, were he not Romeo call'd,
            Retain that dear perfection which he owes
            Without that title. Romeo, doff thy name,
            And for that name which is no part of thee
            Take all myself.

            ROMEO

            I take thee at thy word:
            Call me but love, and I'll be new baptized;
            Henceforth I never will be Romeo.

            JULIET

            What man art thou that thus bescreen'd in night
            So stumblest on my counsel?

            ROMEO

            By a name
            I know not how to tell thee who I am:
            My name, dear saint, is hateful to myself,
            Because it is an enemy to thee;
            Had I it written, I would tear the word.

            JULIET

            My ears have not yet drunk a hundred words
            Of that tongue's utterance, yet I know the sound:
            Art thou not Romeo and a Montague?

            ROMEO

            Neither, fair saint, if either thee dislike.

            JULIET

            How camest thou hither, tell me, and wherefore?
            The orchard walls are high and hard to climb,
            And the place death, considering who thou art,
            If any of my kinsmen find thee here.

            ROMEO

            With love's light wings did I o'er-perch these walls;
            For stony limits cannot hold love out,
            And what love can do that dares love attempt;
            Therefore thy kinsmen are no let to me."
                );
            #endregion
            m_dummyspeechaudio.SpeakAsync(builder);
        }
        /// <summary>
        /// Handler for MSG_QUERY
        /// </summary>
        /// <param name="message">The message received</param>
        protected async void MsgQuery(dynamic message)
        {
            var data = message["data"];
            MycroftSpeaker speaker = speakers[data["targetSpeaker"]];
            if (speaker.Status != "up")
            {
                await QueryFail(message["id"], "Target speaker is " + speaker.Status);
            }
            else
            {
                var text = data["text"];
                PromptBuilder prompt = new PromptBuilder(new System.Globalization.CultureInfo("en-GB"));
                prompt.StartVoice(VoiceGender.Female, VoiceAge.Adult, 0);
                foreach (var phrase in text)
                {
                    prompt.AppendText(phrase["phrase"]);
                    prompt.AppendBreak(new TimeSpan((int)(phrase["delay"] * 10000000)));
                }
                prompt.EndVoice();
                try
                {
                    prompt.AppendAudio("lutz.wav");
                }
                catch
                {

                }
                Thread t = new Thread(Listen);
                t.Start(new { speaker = speaker, prompt = prompt });

                await Query("audioOutput", "stream_tts", new { ip = ipAddress, port = speaker.Port }, new string[] { speaker.InstanceId });
            }
        }
Exemple #33
0
 private void Play(object text)
 {
     SpeechSynthesizer synth = new SpeechSynthesizer();
     PromptBuilder builder = new PromptBuilder(new System.Globalization.CultureInfo("zh-CN"));
     synth.SetOutputToDefaultAudioDevice();
     if (SelectVoice.Items.Count > 0)
     {
         synth.SelectVoice(SelectVoice.SelectedItem.ToString()); //语音选择
     }
     synth.Rate = Convert.ToInt32(voiceRate.Text);//语速
     builder.AppendText(text.ToString());
     synth.Speak(builder);
     synth.Dispose();
 }
Exemple #34
0
 public void TTS(string text)
 {
     PromptBuilder pb = new PromptBuilder();
     pb.AppendText("This is a date");
     pb.AppendBreak();
     pb.AppendTextWithHint("31-12-2007", SayAs.DayMonthYear);
     //PromptBuilder(pb);
 }
        public Task SayText(string text, TextToSpeechVoice voice, SpeechRate rate, SpeechVolume volume)
        {
            PromptStyle style = new PromptStyle();

            switch (rate)
            {
            case SpeechRate.ExtraFast: style.Rate = PromptRate.ExtraFast; break;

            case SpeechRate.Fast: style.Rate = PromptRate.Fast; break;

            case SpeechRate.Medium: style.Rate = PromptRate.Medium; break;

            case SpeechRate.Slow: style.Rate = PromptRate.Slow; break;

            case SpeechRate.ExtraSlow: style.Rate = PromptRate.ExtraSlow; break;
            }

            switch (volume)
            {
            case SpeechVolume.Default: style.Volume = PromptVolume.Default; break;

            case SpeechVolume.ExtraLoud: style.Volume = PromptVolume.ExtraLoud; break;

            case SpeechVolume.Loud: style.Volume = PromptVolume.Loud; break;

            case SpeechVolume.Medium: style.Volume = PromptVolume.Medium; break;

            case SpeechVolume.Soft: style.Volume = PromptVolume.Soft; break;

            case SpeechVolume.ExtraSoft: style.Volume = PromptVolume.ExtraSoft; break;
            }

            PromptBuilder prompt = new PromptBuilder();

            prompt.StartStyle(style);
            prompt.AppendText(text);
            prompt.EndStyle();

            Task.Run(async() =>
            {
                try
                {
                    using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
                    {
                        if (voice == null)
                        {
                            voice = this.GetInstalledVoices().FirstOrDefault();
                        }

                        if (voice != null)
                        {
                            synthesizer.SelectVoice(voice.Name);
                        }

                        Prompt promptAsync = synthesizer.SpeakAsync(prompt);
                        while (!promptAsync.IsCompleted)
                        {
                            await Task.Delay(1000);
                        }
                    }
                }
                catch (Exception ex) { Logger.Log(ex); }
            });

            return(Task.FromResult(0));
        }