/// <summary>Speaks the specified text to the specified file.</summary> /// <param name="text">The text to be spoken.</param> /// <param name="audioPath">The file to which the spoken text should be written.</param> /// <remarks>Uses the Microsoft Speech libraries.</remarks> private void SpeakToFile(string text, FileInfo audioPath) { SpFileStream spFileStream = new SpFileStream(); try { // Create the speech engine and set it to a random installed voice SpVoice speech = new SpVoice(); ISpeechObjectTokens voices = speech.GetVoices(string.Empty, string.Empty); speech.Voice = voices.Item(NextRandom(voices.Count)); // Set the format type to be heavily compressed. This both decreases download // size and increases distortion. SpAudioFormatClass format = new SpAudioFormatClass(); format.Type = SpeechAudioFormatType.SAFTGSM610_11kHzMono; spFileStream.Format = format; // Open the output stream for the file, speak to it, and wait until it's complete spFileStream.Open(audioPath.FullName, SpeechStreamFileMode.SSFMCreateForWrite, false); speech.AudioOutputStream = spFileStream; speech.Speak(text, SpeechVoiceSpeakFlags.SVSFlagsAsync); speech.Rate = -5; speech.WaitUntilDone(System.Threading.Timeout.Infinite); } finally { // Close the output file spFileStream.Close(); } }
public void Run() { var speaker = new SpVoice(); VoiceType = NeoSpeechVoiceType.Anna; speaker.Voice = NeoSpeech.GetVoice(VoiceType); speaker.Rate = Rate; SpFileStream stream = new SpFileStream(); try { stream.Format.Type = SpeechAudioFormatType.SAFT48kHz16BitStereo; stream.Open(FileName + ".wav", SpeechStreamFileMode.SSFMCreateForWrite, true); speaker.AudioOutputStream = stream; speaker.Speak(Text,SpeechVoiceSpeakFlags.SVSFlagsAsync); speaker.WaitUntilDone(Timeout.Infinite); stream.Close(); Thread.Sleep(100); MP3Engine.Wav2Mp3(FileName + ".wav", FileName + ".mp3"); System.IO.File.Delete(FileName + ".wav"); } catch (System.Runtime.InteropServices.COMException ex) { stream.Close(); throw ex; } finally { } }
/** * Export to tts engine * Copyright (C) David Futcher 2007 * <bobbocanfly at gmail dot com> * http://text2speech.sourceforge.net * This function is part of Text2Speech. */ public void export(string q, string a, string file) { if (Settings.getBool ("dumpTooltips") == false) { return; } int pause = Settings.getInt ("speakingPauseInt", 5) * 1000; file = this.sanitizeFilename (file) + ".wav"; SpVoice expVoice = new SpVoice (); SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite; SpFileStream SpFileStream = new SpFileStream (); SpFileStream.Open (file, SpFileMode, false); expVoice.AudioOutputStream = SpFileStream; expVoice.Volume = 100; expVoice.Rate = 0; expVoice.Speak ("<speak/><volume level=\"0\">a<volume level=\"100\"><silence msec=\"2000\"/>", SpeechVoiceSpeakFlags.SVSFDefault); expVoice.Speak ("<speak/>" + q, SpeechVoiceSpeakFlags.SVSFDefault); expVoice.Speak ("<speak/><volume level=\"0\">a<volume level=\"100\"><silence msec=\"" + pause.ToString () + "\"/>", SpeechVoiceSpeakFlags.SVSFDefault); expVoice.Speak ("<speak/>" + a, SpeechVoiceSpeakFlags.SVSFDefault); expVoice.Speak ("<speak/><volume level=\"0\">a<volume level=\"100\"><silence msec=\"2000\"/>", SpeechVoiceSpeakFlags.SVSFDefault); SpFileStream.Close (); expVoice = null; }
public static bool SpeechInitialize(IntPtr win, string voice) { try { m_Speak = true; m_SPV = new SpVoice(); if (!string.IsNullOrEmpty(voice)) { ISpeechObjectTokens voices = m_SPV.GetVoices("", ""); foreach (ISpeechObjectToken v in voices) { if (v.GetDescription(0) == voice) { m_SPV.Voice = (SpObjectToken)v; break; } } } else if (voice == null) m_Speak = false; return true; } catch { return false; } }
public UdiskMonitor(string info) : base() { InitializeComponent(); SpVoice spv = new SpVoice(); if (spv == null) return; ISpeechObjectTokens arrVoices = spv.GetVoices(string.Empty, string.Empty); List<string> arrlist = new List<string>(); for (int i = 0; i < arrVoices.Count; i++) { arrlist.Add(arrVoices.Item(i).GetDescription(0)); } cmbVoices.DataSource = arrlist; Point p = new Point(500, 1024); this.Location = p; t = new byte[4]; t[0] = 5; label1.Text = info; speak_Thread = new Thread(new ThreadStart(start_Speak)); speak_Thread.Start(); linkLabel1.Visible = true; linkLabel1.Text = "马上开始扫描"; linkLabel1.LinkColor = Color.Red; }
//private ISpeechObjectTokens voiceInfo; /// <summary> /// constructor /// </summary> public HmfSpeechAssist() { this.tts = new SpVoice(); this.tts.Volume = 100; this.tts.Rate = 0; this.speechFlg = SpeechVoiceSpeakFlags.SVSFlagsAsync | SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak; }
protected void Button1_Click() { //THIS BLOCK WORKS RIGHT SpVoice ob = new SpVoice(); ob.Rate = -100; ob.Speak("Start recognistion", SpeechVoiceSpeakFlags.SVSFDefault); SpStream str = new SpStream(); }
public void Speek() { Console.WriteLine("This test should play a sound."); SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFDefault; var speech = new SpVoice(); speech.Speak("You are being followed", SpFlags); //speech.Speak("You are were eaten by a Grue", SpFlags); }
/// <summary> /// constructor /// </summary> public UcommSpeaker() { voice = new SpVoice(); voice.Volume = 100; voice.Rate = 0; voiceFlag = SpeechVoiceSpeakFlags.SVSFlagsAsync | SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak; speaker = new SpeechSynthesizer(Properties.Settings.Default.AZURE_CLIENT_ID, Properties.Settings.Default.AZURE_CLIENT_SECRET); }
public void OnPingTimeOut(string serverName) { SpVoice speech = new SpVoice(); for (int i=0; i<(int)warningVoiceUpDown.Value; i++) { speech.Speak(string.Format("{0} {1}",serverName, voiceTextBox.Text), SpeechVoiceSpeakFlags.SVSFlagsAsync); } }
public Talker(string description) { m_voice = new SpVoice(); ISpeechObjectTokens tokens = m_voice.GetAudioOutputs(null, null); foreach (ISpeechObjectToken token in tokens) { if (token.GetDescription(0) == description) m_voice.AudioOutput = (SpObjectToken)token; } }
public MainForm() { InitializeComponent(); mVoice = new SpVoice(); mSpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync; mVoice.Priority = SpeechVoicePriority.SVPNormal; rbNormal.Checked = true; mPlaying = false; mNewStart = true; }
public TTSHelper(int volume, int rate) { //param spFileStream = new SpFileStream(); //declaring and Initializing fileStream obj spFileMode = SpeechStreamFileMode.SSFMCreateForWrite; //declaring fileStreamMode as to Create or Write // SpeechVoiceSpeakFlags my_Spflag = SpeechVoiceSpeakFlags.SVSFlagsAsync; // declaring and initializing Speech Voice Flags my_Voice = new SpVoice(); //declaring and initializing SpVoice Class sp_Rate = rate; sp_Volume = volume; my_Spflag = SpeechVoiceSpeakFlags.SVSFlagsAsync; }
/// <summary> /// funcNextFragment is called for every phrase read 0..n-1 and one more time, with a null, when we are done all fragments /// </summary> public MultiPhrasing( SynthesizerWrapper voxWrapper, IEnumerator<UniLangPhrase> enumerator, Action<UniLangPhrase> funcNextFragment) { this.voxWrapper = voxWrapper; this.enumerator = enumerator; this.funcNextFragment = funcNextFragment; vox = voxWrapper.Vox; vox.EndStream += PhraseEnded; }
public Form1() { InitializeComponent(); voice = new SpVoice(); foreach (ISpeechObjectToken Token in voice.GetVoices(string.Empty, string.Empty)) { cmbVoices.Items.Add(Token.GetDescription(49)); } cmbVoices.SelectedIndex = 0; // Not sure how to set voice from this... }
/** * Initializes the Text to Speech and Speech to Text engines. * Finalize commands must be called before the Speech to Text engine will * work. */ public Voice() { this.voice = new SpVoice(); objRecoContext = new SpSharedRecoContext(); objRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler(RecoEvent); grammar = objRecoContext.CreateGrammar(0); menuRule = grammar.Rules.Add("cogitoCommands",SpeechRuleAttributes.SRATopLevel|SpeechRuleAttributes.SRADynamic,1); this.commandCount = 1; this._buffer = new Queue(); }
public SpeechLibStrategy(Options options, int speedRate, ConvertorFactory.SupportedType supportedType) { _options = options; _supportedType = supportedType; Voice = new SpVoice { Rate = speedRate, }; SetVoice(Properties.Settings.Default.VoiceName); }
private void Falar01(int velocidade, int volume, string mensagem) { // Cria o objeto SpVoice speak = new SpVoice(); // Define a velocidade speak.Rate = velocidade; // Define o volume speak.Volume = volume; // Pede uma requisição para falar speak.Speak(mensagem, SpeechVoiceSpeakFlags.SVSFDefault); //Se você deixar essa linha, o texto falará apenas quando terminar o método (método Assíncrono) speak.WaitUntilDone(speak.SynchronousSpeakTimeout); }
public static void GetJobVoice(string job) { Thread.Sleep(10); if (MainWin.TitleLinks.FirstOrDefault(l => l.Source == new Uri("cmd://GoSound", UriKind.Absolute))? .DisplayName != "Выключить звук" || job == null) return; if (Voice != null) { Voice.Pause(); Voice = null; } Voice = new SpVoice(); Voice.Speak(job, (SpeechVoiceSpeakFlags)65); }
private void init_vox() { Vox = new SpVoice(); var voices = Vox.GetVoices(); voiceNames = new string[voices.Count]; for (int i = 0; i < voices.Count; i++) { var voice = voices.Item(i); var name = voice.GetDescription(); voiceNames[i] = name; } Vox.Word += Vox_Word; Vox.EndStream += Vox_EndStream; }
static void Main(string[] args) { SpeechVoiceSpeakFlags flags = SpeechVoiceSpeakFlags.SVSFlagsAsync; SpVoice v = new SpVoice(); if( args.Length > 0 ) { v.Speak(args[0], flags); } else { v.Speak("Please specify what you would like me to say.", flags ); } v.WaitUntilDone(Timeout.Infinite); }
public static string Speek(string word) { string url; if (!CheckWord(word, out url)) { var path = HttpContext.Current.Server.MapPath(url); var voice = new SpVoice(); voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0); var sp = new SpFileStream(); sp.Open(path, SpeechStreamFileMode.SSFMCreateForWrite); voice.AudioOutputStream = sp; voice.Speak(word); voice.WaitUntilDone(System.Threading.Timeout.Infinite); sp.Close(); } return url; }
public static void InitNeoSpeechVoices() { NeoSpeechVoices = new Dictionary<NeoSpeechVoiceType,SpObjectToken>(); try { Dictionary<NeoSpeechVoiceType, SpObjectToken> ObjectTokens = new Dictionary<NeoSpeechVoiceType, SpObjectToken>(); var voice = new SpVoice(); string[] speakers = { "VW Julie", "VW Kate", "VW Paul", "VW Liang", "VW Hui", "Microsoft Lili - Chinese (China)", "Microsoft Anna - English (United States)" }; NeoSpeechVoiceType speaker = NeoSpeechVoiceType.Julie; ISpeechObjectTokens sot = voice.GetVoices(string.Empty, string.Empty); string[] voiceIds = new string[sot.Count]; for (int i = 0; i < sot.Count; i++) { voiceIds[i] = sot.Item(i).GetDescription(1033); if (speakers.Contains(voiceIds[i])) { switch (voiceIds[i]) { case "VW Julie": speaker = NeoSpeechVoiceType.Julie; break; case "VW Kate": speaker = NeoSpeechVoiceType.Kate; break; case "VW Paul": speaker = NeoSpeechVoiceType.Paul; break; case "VW Liang": speaker = NeoSpeechVoiceType.Liang; break; case "VW Hui": speaker = NeoSpeechVoiceType.Hui; break; case "Microsoft Lili - Chinese (China)": speaker = NeoSpeechVoiceType.Lili; break; case "Microsoft Anna - English (United States)": speaker = NeoSpeechVoiceType.Anna; break; default: speaker = NeoSpeechVoiceType.Julie; break; } ObjectTokens.Add(speaker, sot.Item(i)); } } NeoSpeechVoices = ObjectTokens; } catch(Exception ex) { string path = MainForm.AppPath + "\\log"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.AppendAllText(path + "\\log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", ex.Message + "\n\r"); } }
private void btnSpeak_Click(object sender, System.EventArgs e) { //Create a TTS voice and speak. try { SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync; SpVoice Voice = new SpVoice(); if (chkSaveToWavFile.Checked) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "All files (*.*)|*.*|wav files (*.wav)|*.wav"; sfd.Title = "Save to a wave file"; sfd.FilterIndex = 2; sfd.RestoreDirectory = true; if (sfd.ShowDialog()== DialogResult.OK) { SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite; SpFileStream SpFileStream = new SpFileStream(); SpFileStream.Open(sfd.FileName, SpFileMode, false); Voice.AudioOutputStream = SpFileStream; Voice.Speak(txtSpeakText.Text, SpFlags); Voice.WaitUntilDone(Timeout.Infinite); SpFileStream.Close(); } } else { Voice.Speak(txtSpeakText.Text, SpFlags); } } catch(Exception error) { MessageBox.Show("Speak error", error.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } }
static void Main(string[] args) { int inputCounter = 0; string input = ""; string filename = ""; SpVoice voice = new SpVoice(); Console.OutputEncoding = Encoding.UTF8; Console.InputEncoding = Encoding.UTF8; DEBUG("SimpleCommandLine#Main(string[]): Using input encoding: " + Console.InputEncoding.BodyName); DEBUG("SimpleCommandLine#Main(string[]): Using output encoding: " + Console.OutputEncoding.BodyName); while ((input = Console.ReadLine()) != null) { DEBUG("SimpleCommandLine#Main(string[]): Read: " + input); input = input.Trim(); if (input.Length == 0) { return; } inputCounter++; if ((inputCounter % 2) == 0) { if (say(filename, input, voice)) { Console.Out.WriteLine("OK"); Console.Out.Flush(); } else { return; } } else { filename = input; } } }
static bool say(string filename, string sent, SpVoice voice) { SpFileStream fileStream = null; bool success = true; try { SpeechVoiceSpeakFlags flags = SpeechVoiceSpeakFlags.SVSFIsXML; //SpeechVoiceSpeakFlags flags = SpeechVoiceSpeakFlags.SVSFIsNotXML; //SpVoice voice = new SpVoice(); SpeechStreamFileMode fileMode = SpeechStreamFileMode.SSFMCreateForWrite; fileStream = new SpFileStream(); fileStream.Open(filename, fileMode, false); // audio output /* voice.Speak(sent, flags); voice.WaitUntilDone(Timeout.Infinite); */ // file output voice.AudioOutputStream = fileStream; voice.Speak(sent, flags); voice.WaitUntilDone(Timeout.Infinite); } catch (Exception error) { success = false; Console.Error.WriteLine("Error speaking sentence: " + error); Console.Error.WriteLine("error.Data: " + error.Data); Console.Error.WriteLine("error.HelpLink: " + error.HelpLink); } finally { if (fileStream != null) { fileStream.Close(); } } return success; }
static void Main(string[] args) { SpVoice voice = new SpVoice(); string esc = "n"; do { Console.WriteLine("Napisz tekst do przeczytania"); string command = Console.ReadLine(); voice.Speak(command, SpeechVoiceSpeakFlags.SVSFlagsAsync); Console.WriteLine("Zakończ: 't' - tak 'n' - nie"); esc = Console.ReadLine(); } while (esc != "t"); //Obdzekt o = new Obdzekt(); //o.cos = 3; //o.nazwa = "macin"; //Console.WriteLine(o.nazwa); //Console.WriteLine(o.cos); ////o.JakasMetoda("NIE macin"); ////o.Foo(2); ////o.Bar(o); ////Metody.Foo(o); ////Obdzekt oo = Metody.Bar(o); ////Obdzekt oo = Metody.Clone(o); //Obdzekt oo = Metody.Clone2(o); //Console.WriteLine(oo.nazwa); //Console.WriteLine(oo.cos); //oo.nazwa = "cycki"; //oo.cos = 1500100900; //Console.WriteLine(oo.nazwa); //Console.WriteLine(oo.cos); //Console.ReadKey(true); }
public Map(List<string[]> db) { InitializeComponent(); voice = new SpVoice(); voice.Rate = -6; data = new List<string[]>(db); id = 0; Fix(); for (int a = 0; a < 15; a++) for (int b = 0; b < 5; b++) addLabel(b, a); for (int c = 0; c < 11; c++) for (int d = 0; d < 3; d++) addLabel(6 + d, c); fn = new System.Drawing.Font("HGPゴシックE", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); RefreshLabel(); }
/** * Speak balloon tip */ public void SpeakBalloonTip(string q, string a, bool speak) { if (!speak) { return; } int pause = Settings.getInt ("speakingPauseInt", 5) * 1000; SpVoice _voice = new SpVoice (); _voice.Speak ("<speak/>" + q, SpeechVoiceSpeakFlags.SVSFDefault); _voice.Speak ("<speak/><volume level=\"0\">a<volume level=\"100\"><silence msec=\"" + pause.ToString () + "\"/>", SpeechVoiceSpeakFlags.SVSFDefault); _voice.Speak ("<speak/>" + a, SpeechVoiceSpeakFlags.SVSFDefault); _voice = null; try { this.export (q, a, q); } catch (Exception ex) { MessageBox.Show ("Error: " + ex.Message); return; } GC.Collect (); }
private void btSave_Click(object sender, EventArgs e) { if(txtSpeach.Text == "") { CustomMessageBox.CustomMessageBox.Show("文本无内容,无法保存","错误",CustomMessageBox.CustomMessageBox.MsgBoxButtons.OK,CustomMessageBox.CustomMessageBox.MsgBoxIcons.Error); return; } else { saveFileDialog1.FileName = ""; saveFileDialog1.Filter = "无损音乐格式(*.wav)|*.wav"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { SpVoice spv = new SpVoice(); if (spv == null) return; SpFileStream cpFileStream = new SpFileStream(); cpFileStream.Open(saveFileDialog1.FileName, SpeechStreamFileMode.SSFMCreateForWrite, false); spv.AudioOutputStream = cpFileStream; spv.Voice = spv.GetVoices(string.Empty, string.Empty).Item(cmbVoices.SelectedIndex); spv.Volume = trVolume.Value; spv.Speak(txtSpeach.Text, SpeechVoiceSpeakFlags.SVSFDefault); cpFileStream.Close(); System.IO.FileInfo f = new System.IO.FileInfo(saveFileDialog1.FileName); if (File.Exists(saveFileDialog1.FileName)) { CustomMessageBox.CustomMessageBox.Show(f.Name + " 保存成功", "提示", CustomMessageBox.CustomMessageBox.MsgBoxButtons.OK, CustomMessageBox.CustomMessageBox.MsgBoxIcons.Info); } else { CustomMessageBox.CustomMessageBox.Show(f.Name + " 保存失败", "警告", CustomMessageBox.CustomMessageBox.MsgBoxButtons.OK, CustomMessageBox.CustomMessageBox.MsgBoxIcons.Error); } } } }
void Start() { voice = new SpVoice(); //voice = new SpVoice(); }
private void DergiHaber_KeyDown(object sender, KeyEventArgs e) { //klavyeden 'Y' tuşuna basıldığında seçilen başlığın içeriği okutuluyor. if (e.KeyCode == Keys.Y) { //timer2 durdularak içerik okutuluyor böylece dergi başlıkları okuması duruyor. timer2.Stop(); //veritabanından bir önceki formda seçilen derginin rss datası çekiliyor. SqlCommand komut1 = new SqlCommand("select DergiRSS from Dergiler where DergiAD='" + dergiHbrLbl.Text + "'", bgl.baglanti()); SqlDataReader dr1 = komut1.ExecuteReader(); while (dr1.Read()) { //çekilen rss datası okutuluyor. XmlTextReader xmlicerikoku = new XmlTextReader(dr1["DergiRSS"].ToString()); while (xmlicerikoku.Read()) { //çekilen rss datasındaki dergi başlıkları çekiliyor if (xmlicerikoku.Name == "title") { //okunan başlık oluşturulan dizide 0.sütuna yazılıyor. dizi[titleindex, 0] = xmlicerikoku.ReadString(); //kullanıcının seçtiği başlık kontrol işlemi if (dizi[titleindex, 0] == lblOku.Text) { //seçilen başlık için tutma işlemi yapılıyor. secilenbaslikindex = titleindex; /* Test İşlemi. * MessageBox.Show("secilen:" + secilenbaslikindex); * MessageBox.Show("secilen:" + dizi[secilenbaslikindex, 0]); */ } //diziye sırayla ekleme yapması için 1 arttırılıyor. titleindex++; } //çekilen rss datasındaki dergi içerikleri çekiliyor if (xmlicerikoku.Name == "description") { //okunan içerikler oluşturulan dizide 1.sütuna yazılıyor. dizi[descriptionindex, 1] = xmlicerikoku.ReadString(); //kullanıcının seçtiği başlık indexi bizim içerik indeximize eşit mi kontrol ediliyor. if (secilenbaslikindex == descriptionindex) { //seçili olan başlığı doğruya richTextBox'ımızın içine içeriğimizi yazdırıyoruz. richTextBox1.Text = dizi[descriptionindex, 1]; /*Test işlemi. * MessageBox.Show("secilen:" + dizi[descriptionindex, 1]); * MessageBox.Show("secilen:" + descriptionindex); */ } //diziye sırayla ekleme yapılıyor. descriptionindex++; } } } //seçilen başlığın içeriği okutuluyor. SpVoice icerikokutma = new SpVoice(); icerikokutma.Speak(richTextBox1.Text); //içerik okutulduktan sonra kalan başlıktan devam etmesi sağlanıyor. i = kalanyer + 1; //tekrardan dizi değerleri 0'lanıyor. titleindex = 0; descriptionindex = 0; //timer2 başlatılarak kaldığı yerden haber başlıkları okutulmaya devam ediyor. timer2.Start(); //veri tabanı bağlantısı kapatılıyor. bgl.baglanti().Close(); } //Eğer Tüm Dergi Okunmuşsa Klavyeden 'T' tuşuna basıldığında tekrardan tüm haber başlıklarını okur. if (e.KeyCode == Keys.T) { //timer2'de Dergiler listboxa ekleniyor.O yüzden i değişkeni sıfırlayıp timerımızı başlatıyoruz. i = 0; timer2.Start(); } //Klavyeden 'B' tuşuna basıldığında form kapanıp bir önceki form açılmaktadır. if (e.KeyCode == Keys.B) { this.Close(); } }
/// <summary> /// Inits the speech lib object, this needs to be on the awake (before Start) because the LE will call RunSpeech on Start. /// /// preconditions: /// /// postconditions: voice object will be created. /// </summary> private void Awake() { Debug.Log(string.Format("TextToSpeech::Start")); voice = new SpVoice(); }
//Hàm phát âm một từ tiếng Anh private void btnSpeakE_Click(object sender, EventArgs e) { SpVoice phatam = new SpVoice(); phatam.Speak(txbEng.Text, SpeechVoiceSpeakFlags.SVSFDefault); }
public static void Main(string[] argv) { int scriptureReferenceVerseCount = -1; string exceptionMessage = null; string scriptureReference = null; string[][] scriptureReferenceArray = null; StringBuilder scriptureReferenceText = null; StringBuilder uriCrosswalkHtml = null; StringBuilder uriCrosswalkXml = null; StringBuilder[] scriptureReferenceBookChapterVersePrePostCondition = null; StringBuilder[] scriptureReferenceBookChapterVersePrePostSelect = null; StringBuilder scriptureReferenceBookChapterVersePrePostQuery = null; IDataReader iDataReader = null; ScriptureReferenceBookChapterVersePrePost[] scriptureReferenceBookChapterVersePrePost = null; if (argv.Length < 1) { return; } else { scriptureReference = argv[0]; } ScriptureReference.ConfigurationXml ( filenameConfigurationXml, ref exceptionMessage, ref DatabaseConnectionString ); System.Console.WriteLine(DatabaseConnectionString); ScriptureReference.ScriptureReferenceParser ( new string[] { scriptureReference }, DatabaseConnectionString, ref exceptionMessage, ref scriptureReferenceBookChapterVersePrePost, ref scriptureReferenceArray, ref uriCrosswalkHtml, ref uriCrosswalkXml ); ScriptureReference.ScriptureReferenceQuery ( DatabaseConnectionString, ref exceptionMessage, ref scriptureReferenceBookChapterVersePrePost, ref iDataReader, ref scriptureReferenceVerseCount, ref scriptureReferenceText, ref scriptureReferenceBookChapterVersePrePostCondition, ref scriptureReferenceBookChapterVersePrePostSelect, ref scriptureReferenceBookChapterVersePrePostQuery ); if (iDataReader != null) { iDataReader.Close(); } DataSet dataSet = new DataSet(); UtilityDatabase.DatabaseQuery ( DatabaseConnectionString, ref exceptionMessage, ref dataSet, scriptureReferenceBookChapterVersePrePostQuery.ToString(), CommandType.Text ); StringBuilder sbScriptureReferenceVerseText = new StringBuilder(); foreach (DataTable dataTable in dataSet.Tables) { foreach (DataRow dataRow in dataTable.Rows) { sbScriptureReferenceVerseText.Append(dataRow["verseText"]); } } System.Console.WriteLine(sbScriptureReferenceVerseText); SpVoice spVoice = new SpVoice(); spVoice.Speak ( sbScriptureReferenceVerseText.ToString(), SpeechVoiceSpeakFlags.SVSFlagsAsync ); spVoice.WaitUntilDone(Timeout.Infinite); }
protected override void OnAfterLoad() { voice = new SpVoice(); }
public void Speak(string s) { SpVoice speech = new SpVoice(); speech.Speak(s, SpeechVoiceSpeakFlags.SVSFDefault); }
public ActionResult Profile(string path) { HttpClient httpClient = new HttpClient(); httpClient.BaseAddress = new Uri("http://localhost:18080"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.GetAsync("epione-jee-web/api/doctolib?path=" + path).Result; if (response.IsSuccessStatusCode) { SpVoice sp = new SpVoice(); if (path.Contains("clinique") || path.Contains("hopital") || path.Contains("centre") || path.Contains("cabinet") || path.Contains("etablissement") || path.Contains("maison")) { DoctolibOtherVM other = response.Content.ReadAsAsync <DoctolibOtherVM>().Result; var groups = other.lstDoctors.GroupBy(x => x.speciality, i => i, (key, v) => new GroupedItem { GroupName = key, Items = v }); ViewBag.result = other; ViewBag.groups = groups; Task.Delay(2000).ContinueWith(name => { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>Welcome to " + other.speciality + " of <voice xml:lang='fr-FR' gender='female'> " + other.name + " </voice> . Located in <voice xml:lang='fr-FR' gender='female'> " + other.address + " </voice> </speak>"); sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>This " + other.speciality + " contain " + groups.Count() + " speciality and " + other.lstDoctors.Count() + " doctors in total. </speak>"); foreach (GroupedItem group in groups) { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>" + group.Items.Count() + " " + group.GroupName + ".</speak>"); foreach (DoctolibVM elem in group.Items) { if (group.Items.ToList().IndexOf(elem) == 0 || group.Items.ToList().IndexOf(elem) < group.Items.Count() - 1) { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>" + elem.name + "</speak>"); } else { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>and " + elem.name + "</speak>"); } } } }); } else { DoctolibDoctorVM doctor = response.Content.ReadAsAsync <DoctolibDoctorVM>().Result; ViewBag.result = doctor; Task.Delay(2000).ContinueWith(name => { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>Welcome to " + doctor.name + " profile </speak>"); Task.Delay(500).ContinueWith(spe => { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>Speciality " + doctor.speciality + " </speak>"); Task.Delay(500).ContinueWith(location => { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>Located in <voice xml:lang='fr-FR' gender='female'> " + doctor.address + " </voice></speak>"); Task.Delay(500).ContinueWith(desc => { sp.Speak("<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>Descripted as " + doctor.description + " </speak>"); }); }); }); }); } } else { ViewBag.result = "error"; } return(View()); }
internal Speak() { _voice = new SpVoice(); }
//sự kiện click vào button nghe private void btnnghe_Click(object sender, EventArgs e) { SpVoice voice = new SpVoice(); voice.Speak(tbtratu.Text, SpeechVoiceSpeakFlags.SVSFDefault); }
public briefing() { InitializeComponent(); //initialise the ticks for (int i = 0; i < ticks.Length; i++) { ticks[i] = 0; } //MessageBox.Show(actTick.ToString(),"debug",MessageBoxButton.OK); //place this code to 'print' variables //get date for new file DateTime d = new DateTime(); d = DateTime.Now; string ds = d.ToString("yyyy-M-d"); //create the file and write the briefing string fn = ds + "_briefing.txt"; //TODO change logic (read/write can come outside of condition) if (!File.Exists("briefings\\" + fn)) { File.Create("briefings\\" + fn).Close(); string temp = File.ReadAllText("setup.txt"); File.WriteAllText("briefings\\" + fn, temp); } else { string temp = File.ReadAllText("setup.txt"); File.WriteAllText("briefings\\" + fn, temp); } pth = "briefing\\" + fn; //TODO checkboxes and labels (refactor when working) dailygoalcheck.Content = MainWindow.dailyGoal; weeklygoalcheck.Content = MainWindow.weeklyGoal; monthlygoalcheck.Content = MainWindow.monthlyGoal; goodcheck.Content = MainWindow.good; badcheck.Content = MainWindow.bad; fixcheck.Content = MainWindow.fix; gratefulcheck.Content = MainWindow.grateful; excitedcheck.Content = MainWindow.excited; forwardcheck.Content = MainWindow.lookingForward; exercisecheck.Content = MainWindow.exercise; wowcheck.Content = MainWindow.wow; remembercheck.Content = MainWindow.remember; actcheck.Content = MainWindow.act; //TODO string conclusion = File.ReadAllText("setup.txt").Split('=')[36]; //num of headlines this.Show(); //speech code goes here //create the url string strURL = "http://www.bbc.co.uk/news"; //create a voice object SpVoice voice = new SpVoice(); //check internet connection bool connected = checkInternet("http://www.google.com"); /*delete to add voice * if (connected) * { * //create a webclient to scrape with * WebClient wc = new WebClient(); * //download the html as a string * string markup = wc.DownloadString(strURL); * // create the regex to search for paragraph text * Regex regex = new Regex("(<p.*?>)(.*?)(?=</p>)"); * // check for matches and create a collection * MatchCollection hlmatches = regex.Matches(markup); * for (int i = 0; i < MainWindow.headlines; i++) * { * //check that its not a paragraph about cookies * Regex cookieCheck = new Regex("Cookie|cookie"); * // build this string * string hl = hlmatches[i].ToString(); * //check for cookies * if (!cookieCheck.IsMatch(hl)) * { * voice.Speak(hl); * }//TODO test this with new logic * } * // get the weather * strURL = "http://www.bbc.co.uk/weather"; * regex = new Regex("(?<=headline.*?>)(.*?)(?=</p>)"); * markup = wc.DownloadString(strURL); * Match wMatch = regex.Match(markup); * voice.Speak(wMatch.ToString()); * } * else * { * voice.Speak("I could not connect to the news website, sorry"); * } * voice.Speak("You're goal for the day is " + MainWindow.dailyGoal); * Thread.Sleep(1000); * voice.Speak("your weekly goal is " + MainWindow.weeklyGoal); * Thread.Sleep(1000); * voice.Speak("your monthly goal is " + MainWindow.monthlyGoal); * Thread.Sleep(1000); * voice.Speak("you are feeling " + MainWindow.feeling + "out of ten"); * Thread.Sleep(1000); * voice.Speak(MainWindow.good + " was good yesterday"); * Thread.Sleep(1000); * voice.Speak(MainWindow.bad + " was bad yesterday"); * Thread.Sleep(1000); * voice.Speak("you will " + MainWindow.fix +" to fix this"); * Thread.Sleep(1000); * voice.Speak("you are grateful for " + MainWindow.grateful); * Thread.Sleep(1000); * voice.Speak("you are excited about " + MainWindow.excited); * Thread.Sleep(1000); * voice.Speak("you are looking forward to " + MainWindow.lookingForward); * Thread.Sleep(1000); * voice.Speak("you will exercise with " + MainWindow.exercise); * Thread.Sleep(1000); * voice.Speak("you will wow people by "+MainWindow.wow); * Thread.Sleep(1000); * voice.Speak("do not forget "+MainWindow.remember); * Thread.Sleep(1000); * voice.Speak("you need to act " + MainWindow.act); * Thread.Sleep(1000); * voice.Speak("okay thats it, now finish your coffee, take your vitamins, drink some water, give me 50 and have a shower maggot!");*/ }
/// <summary> /// Speaks the provided text out load /// </summary> /// <param name="text"></param> public void Speak(string text) { SpVoice voice = new SpVoice(); voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault); }
/// <summary> /// References the COM dll SpeechLib.dll, when run speaks whatever is passed in as string /// </summary> public static void TestComMethod() { SpVoice voice = new SpVoice(); voice.Speak("Hello World", SpeechVoiceSpeakFlags.SVSFDefault); }
private void btnSpeech_Click(object sender, EventArgs e) { SpVoice voice = new SpVoice(); voice.Speak(txtNhap.Text, SpeechVoiceSpeakFlags.SVSFDefault); }
void Start() { mTextField = GetComponent <UnityEngine.UI.InputField>(); voice = new SpVoice(); }
void Start() { voice = new SpVoice(); input = GameObject.Find("InputField1").GetComponent <InputField>(); }
public void pause() { voice = new SpVoice(); voice.Pause(); }
protected void Page_Load(object sender, EventArgs e) { if (Session["action"] != null) { voice.Attributes.CssStyle.Add("visibility", "visible"); Label5.Text = Session["action"].ToString(); SpVoice voice1; voice1 = new SpVoice(); voice1.Volume = 100; // 0...100 voice1.Rate = -4; // -10...10 string reply = Request.QueryString["reply"]; string link = Request.QueryString["link"]; if (reply != null) { string sel = "select * from Answer"; SqlDataAdapter da = new SqlDataAdapter(sel, con); DataSet ds = new DataSet(); da.Fill(ds); int count = ds.Tables[0].Rows.Count; string ques = ds.Tables[0].Rows[0][1].ToString(); string ans = ds.Tables[0].Rows[0][2].ToString(); string url = ds.Tables[0].Rows[0][3].ToString(); if (count > 0) { Button3.Visible = true; speak_text.Text = ques; Label4.Text = ans; if (url != "") { HyperLink2.Visible = true; HyperLink2.NavigateUrl = Convert.ToString(url); } } else { Button3.Visible = false; } if (reply != "none") { voice1.Speak(reply); Label4.Text = reply; // voice.Visible = true; speak_text.Text = ""; //ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "PageLoad()", true); this.HiddenField1.Value = "yes"; } } else { voice.Attributes.CssStyle.Add("visibility", "hidden"); Label5.Text = ""; } } else { voice.Attributes.CssStyle.Add("visibility", "hidden"); Label5.Text = ""; } }
private void button3_Click(object sender, EventArgs e) { SpVoice Speaker = new SpVoice(); Speaker.Speak(textBox1.Text, SpeechVoiceSpeakFlags.SVSFDefault); }
private void msgTimer_Tick(object sender, EventArgs e) { try { //显示的字数长度 int length = (int)((msgStartX - msgCurntX) / (msgStep * 4)); if (ExtendAppContext.Current.StaticMsgList == null) { ExtendAppContext.Current.StaticMsgList = new List <string>(); ExtendAppContext.Current.StaticMsgList.Add("暂无公告信息。"); } string msg = ""; //非紧急公告,即静态公告 if (!isEmgrcMsg) { if (msgIndex == ExtendAppContext.Current.StaticMsgList.Count) { msgIndex = 0; msgCurntX = msgStartX; } msg = ExtendAppContext.Current.StaticMsgList[msgIndex]; //修正起始位置偏移的问题 while ((length <= msg.Length) && (this.CreateGraphics().MeasureString(msg.Substring(0, length), MsgFont).Width < (msgStartX - msgCurntX))) { length++; } if (length > ExtendAppContext.Current.StaticMsgList[msgIndex].Length) { length = ExtendAppContext.Current.StaticMsgList[msgIndex].Length; } //截取需要显示的字符串 curntMsg = ExtendAppContext.Current.StaticMsgList[msgIndex].Substring(0, length); } else { //修正起始位置偏移的问题 while ((length <= noticeMsg.Length) && (this.CreateGraphics().MeasureString(noticeMsg.Substring(0, length), MsgFont).Width < (msgStartX - msgCurntX))) { length++; } if (length > noticeMsg.Length) { length = noticeMsg.Length; } //截取需要显示的字符串 curntMsg = noticeMsg.Substring(0, length); } //计算需要显示的字符长度 int msgLength = (int)this.CreateGraphics().MeasureString(curntMsg, MsgFont).Width; if (msgCurntX + msgLength > 0) { screenBottomPnl.Refresh(); msgCurntX -= msgStep; } //转完一圈,重新获取公告信息 if (msgCurntX + msgLength <= 0) { //msgTimer.Stop(); if (!isEmgrcMsg) { //重新获取静态播报信息列表 QueryParams queryParams = new QueryParams(); queryParams.AddQueryDefines("ScreenNo", OperationEnum.Equal, ExtendAppContext.Current.CurntScreenNo); DataTable staticMsgTable = DataOperator.HttpWebApi <DataResult>(ApiUrlEnum.GetValidMsgData, queryParams).ToDataTable(); List <string> staticListMsg = new List <string>(); if (staticMsgTable != null && staticMsgTable.Rows.Count > 0) { foreach (DataRow row in staticMsgTable.Rows) { if (!row.IsNull("MSG_CONTENT") && !string.IsNullOrEmpty(row["MSG_CONTENT"].ToString())) { staticListMsg.Add(row["MSG_CONTENT"].ToString()); } } ExtendAppContext.Current.StaticMsgList = staticListMsg; } msgIndex++; } // Dictionary<string, string> noticeMsgDict = GetMsgNoticInfo(); if (noticeMsgDict != null && noticeMsgDict.Count > 0 && ExtendAppContext.Current.IsBroadCast) { isEmgrcMsg = true; foreach (KeyValuePair <string, string> kvp in noticeMsgDict) { string[] Info_Count = kvp.Value.Split(',');//通告信息,播报次数 string msgID = kvp.Key; noticeMsg = Info_Count[0]; int count = Convert.ToInt32(Info_Count[1]); SpFlags = DotNetSpeech.SpeechVoiceSpeakFlags.SVSFlagsAsync; Voice = new SpVoice(); Voice.Rate = -4; Voice.Speak(noticeMsg, SpFlags); //Voice.WaitUntilDone(System.Threading.Timeout.Infinite); //可播报次数-1 count -= 1; //更新剩余可播报次数 UpdateMsgDataTable(msgID, count); if (count == 0) { noticeMsgDict.Remove(msgID); } else { noticeMsgDict[msgID] = noticeMsg + "," + count; } break;//一次只播一条 } } else { isEmgrcMsg = false; } msgCurntX = msgStartX; //msgTimer.Start(); } } catch (Exception ex) { ExceptionHandler.Handle(ex); } }
private void SaveFile(string FileName, string Content) { try { DelFile(FileName); if (SingletonInfo.GetInstance().IsNationFlag) { string[] FileNamesp = FileName.Split('.'); FileName = FileNamesp[0] + ".wav"; } SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync; SpVoice Voice = new SpVoice(); Voice.Rate = SingletonInfo.GetInstance()._rate; string filename = FileName; string filenametmp = FileName.Split('.')[0] + "tmp.wav"; string texttxt = Content; SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite; SpFileStream SpFileStream = new SpFileStream(); SpFileStream.Open(filenametmp, SpFileMode, false); Voice.AudioOutputStream = SpFileStream; Voice.Speak(texttxt, SpFlags); Voice.WaitUntilDone(Timeout.Infinite); SpFileStream.Close(); int nFrontPackCnt = SingletonInfo.GetInstance()._nFrontPackCnt; int nTailPackCnt = SingletonInfo.GetInstance()._nTailPackCnt; int de = NativeMethods.InsertBlankAudio(filename, filenametmp, nFrontPackCnt, nTailPackCnt); DelFile(filenametmp); FileInfo MyFileInfo = new FileInfo(filename); float dirTime = (float)MyFileInfo.Length / 32000; string[] filepathname = FileName.Split('\\'); string filenamesignal = ""; if (SingletonInfo.GetInstance().IsNationFlag) { filenamesignal = filepathname[filepathname.Length - 1].Split('.')[0] + ".mp3"; } else { filenamesignal = filepathname[filepathname.Length - 1]; } string senddata = "PACKETTYPE~TTS|FILE~" + filenamesignal + "|TIME~" + ((uint)dirTime).ToString(); LogMessage(senddata); #region 如果是需要mp3文件 则需要调用ffmepg if (SingletonInfo.GetInstance().IsNationFlag) { //转换MP3 string wavfilename = filenamesignal.Replace(".mp3", ".wav"); string fromMusic = SingletonInfo.GetInstance()._path + "\\" + wavfilename; //转换音乐路径 string toMusic = SingletonInfo.GetInstance()._path + "\\" + filenamesignal; //转换后音乐路径 int bitrate = 128 * 1000; //恒定码率 string Hz = "44100"; //采样频率 ExcuteProcess("ffmpeg.exe", "-y -ab " + bitrate + " -ar " + Hz + " -i \"" + fromMusic + "\" \"" + toMusic + "\""); // Thread.Sleep(100); File.Delete(fromMusic); //转换完成 } #endregion #region ftp文件传输 20190107新增 if (SingletonInfo.GetInstance().FTPEnable) { string ftppath = filenamesignal; string path = SingletonInfo.GetInstance()._path + "\\" + filenamesignal; SingletonInfo.GetInstance().ftphelper.UploadFile(path, ftppath);//阻塞式非线程模式 } #endregion SendMQMessage(senddata); } catch (Exception ex) { LogHelper.WriteLog(typeof(MainForm), "SaveFile处理异常:" + ex.ToString() + "----------" + ex.InnerException + "-------" + ex.StackTrace + "-------" + ex.Message, "2"); } }
void Update() { if (flag) { flag = false; recognization(); } if (input.text.IndexOf("结束对话") > -1) { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的", SpeechVoiceSpeakFlags.SVSFlagsAsync); input.text = ""; show.text = ""; dictationRecognizer.Dispose(); PhraseRecognitionSystem.Restart(); rest = true; } if ((input.text.IndexOf("自我介绍") > -1) || (input.text.IndexOf("跟大家问好") > -1) || (input.text.IndexOf("你是谁") > -1)) { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) show.text = "大家好 我的名子是小白 我是一個正在努力學習的人工智慧管家唷"; voice.Speak(show.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); input.text = ""; show.text = ""; action = "Introduction"; } time_f += Time.deltaTime; time_i = (int)time_f; if (time_i == 2) { if (input.text != "") { if (face_flag == 1) { face_recognize(); } else { //OnDestroy(); EnterPlayerName(); } rest_count = 0; } else if (!rest) { rest_count += 1; Debug.Log(rest_count); if (rest_count == 10) { dictationRecognizer.Dispose(); PhraseRecognitionSystem.Restart(); rest_count = 0; rest = true; Debug.Log("休息"); } } time_f = 0f; time_i = 0; } clock_time_f += Time.deltaTime; clock_time_i = (int)clock_time_f; if (clock_time_i == 5) { clock_time_f = 0f; clock_time_i = 0; //clock(); Reminder(); //charactormood(); //呼叫肚子餓 } }
IEnumerator chat() { WWW www = new WWW(_path); yield return(www); adf = www.text; if (adf == "1") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的你要新增甚麼時候", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "14") { //show.text = "請告訴我時間點"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("請告訴我時間點", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "2") { //show.text = "好的你要新增甚麼事件"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的你要新增甚麼事件", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "3") { //show.text = "好的你要甚麼時候叫你呢"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的你要甚麼時候叫你呢", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "4") { //show.text = "最近有安排其他行程確定還要新增行程嗎"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("最近有安排其他行程確定還要新增行程嗎", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "11") { //show.text = "好的你要刪除甚麼時候或甚麼事件呢"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的你要刪除甚麼時候或甚麼事件呢", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "13") { check_deitinerary(); } else if (adf == "9") { check_itinerary(); } else if (adf == "5") { song_adf = "1"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的要聽什麼", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "6") { youtube_mov(); voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "7") { face_flag = 1; face_recognize(); adf = "0"; } else if (adf == "8") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的", SpeechVoiceSpeakFlags.SVSFlagsAsync); Application.LoadLevel("rotatedPathsLevel"); } else if (adf == "10") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的你要查詢哪時候或甚麼事件呢", SpeechVoiceSpeakFlags.SVSFlagsAsync); itinerary_flag = true; } else if (adf == "15") { wiki(); voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "16" || adf == "18") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("是否要為你開燈?", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "17") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的,你想開哪裡的電燈?", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "19") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("我不懂,請問是甚麼意思", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "20") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("請問目的站和終點站是哪裡", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (adf == "21") { voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("請問要查詢哪時候", SpeechVoiceSpeakFlags.SVSFlagsAsync); train_flag = true; } else { if (song_adf == "1") { Application.OpenURL("https://www.youtube.com/" + www.text); song_adf = "0"; adf = "0"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak("好的", SpeechVoiceSpeakFlags.SVSFlagsAsync); } else { adf = "0"; if (www.text.IndexOf("天氣") > -1) { if (www.text.IndexOf("晴時多雲") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("sun"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("sun"); } else if (www.text.IndexOf("陰時多雲短暫陣雨或雷雨") > -1 || www.text.IndexOf("陰短暫陣雨或雷雨") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("rain_light"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("rain_light"); } else if (www.text.IndexOf("多雲時陰") > -1 || www.text.IndexOf("陰時多雲") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("gray_cloud"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("gray_cloud"); } else if (www.text.IndexOf("多雲短暫雨") > -1 || www.text.IndexOf("多雲時陰短暫雨") > -1 || www.text.IndexOf("多雲短暫陣雨") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("cloud_rain"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("cloud_rain"); } else if (www.text.IndexOf("多雲時晴") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("sun_cloud"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("sun_cloud"); } else if (www.text.IndexOf("陰短暫雨") > -1 || www.text.IndexOf("陰時多雲短暫雨") > -1 || www.text.IndexOf("陰有雨") > -1 || www.text.IndexOf("陰短暫陣雨") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("cloud_rain"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("cloud_rain"); } else if (www.text.IndexOf("多雲") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("cloud"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("cloud"); } else if (www.text.IndexOf("陰天") > -1) { m_Sprite.sprite = (Sprite)Resources.Load <Sprite>("gray_cloud"); m_Sprite2.sprite = (Sprite)Resources.Load <Sprite>("gray_cloud"); } show.text = www.text; show.fontSize = 15; show2.text = www.text; show2.fontSize = 15; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); //recognization(); } else if (itinerary_flag == true) { action = "Move_Left"; show.text = www.text; show.fontSize = 15; show2.text = www.text; show2.fontSize = 15; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); itinerary_flag = false; //recognization(); } else if (www.text.IndexOf("高兴") > -1) { action = "Happy"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (www.text.IndexOf("早安") > -1 || www.text.IndexOf("你好") > -1) { action = "greet"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (www.text.IndexOf("喜欢") > -1) { action = "LIKE"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (www.text.IndexOf("空气") > -1) { show.text = www.text; show.fontSize = 15; show2.text = www.text; show2.fontSize = 15; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); } else if (train_flag) { action = "Move_Left"; show.text = www.text; show.fontSize = 15; show2.text = www.text; show2.fontSize = 15; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); } else { //show.text = www.text; adf = "0"; voice = new SpVoice(); voice.Volume = 100; // Volume (no xml) voice.Rate = 0; // Rate (no xml) voice.Speak(www.text, SpeechVoiceSpeakFlags.SVSFlagsAsync); //voice.WaitUntilDone(10000); //dictationRecognizer.Start(); //recognization(); } } } thinking_Sprite.sprite = (Sprite)Resources.Load <Sprite>("None"); input.text = ""; //recognization(); }
protected void Button1_Click(object sender, EventArgs e) { SpVoice voice = new SpVoice(); voice.Speak(TextBox1.Text); }
void Awake() { voice = new SpVoice(); }
//扫码 private void AddGoods() { SpeechVoiceSpeakFlags speakflag = SpeechVoiceSpeakFlags.SVSFlagsAsync; SpVoice voice = new SpVoice(); string num = numberTextBox.Text; ///18位条码和13位条码混合 if (string.IsNullOrEmpty(num) || (num.Length != 13 && num.Length != 18)) { voice.Speak("错误", speakflag); MessageBox.Show("请确认扫码的条码是否正确", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); numberTextBox.Text = ""; return; } ///以后的13的条码 //if(string.IsNullOrEmpty(num) || num.Length != 13) //{ // MessageBox.Show("请确认扫码的条码是否正确", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); // numberTextBox.Text = ""; // return; //} ///扫码扫出来的结果 string serialNumber = ""; float weigth = 0; if (num.StartsWith("28")) { ///13位的条码 //serialNumber = num.Substring(2, 5); //string weightString = num.Substring(7, 5); //weigth = float.Parse(weightString.Insert(2, ".")); ///18位的条码和13位码都有 if (num.Length == 18) { serialNumber = num.Substring(2, 5); string weightString = num.Substring(12, 5); weigth = float.Parse(weightString.Insert(2, ".")); } else //肉类的13位码 { serialNumber = num.Substring(2, 5); string weightString = num.Substring(7, 5); weigth = float.Parse(weightString.Insert(2, ".")); } } else { serialNumber = num; } DataSet ds = (DataSet)this.goodDataGridView.DataSource; bool flag = false; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { string serialNum = this.goodDataGridView[0, i].Value == null ? "" : this.goodDataGridView[0, i].Value.ToString(); if (serialNum.Equals(serialNumber)) { string nums = this.goodDataGridView[4, i].Value == null || "".Equals(this.goodDataGridView[4, i].Value) ? "0" : this.goodDataGridView[4, i].Value.ToString(); string orderNums = this.goodDataGridView[3, i].Value.ToString(); flag = true; ///start 减去判断 if ((string.IsNullOrEmpty(nums) || "0".Equals(nums)) && !calFlag) { voice.Speak("错误", speakflag); MessageBox.Show("此商品份数为0无法进行减去操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); numberTextBox.Text = ""; calFlag = true; calculateButton.Text = "加(F1)"; return; } else { orderSorte orderSorte = new orderSorte(); orderSorte.createTime = DateTime.Now; orderSorte.updateTime = DateTime.Now; orderSorte.address = ConstantUtil.street; orderSorte.goods_id = this.goodDataGridView.Rows[i].Cells[5].Value == null ? "" : this.goodDataGridView.Rows[i].Cells[5].Value.ToString(); orderSorte.id = Guid.NewGuid().ToString(); orderSorte.goods_name = this.goodDataGridView.Rows[i].Cells[2].Value == null ? "" : this.goodDataGridView.Rows[i].Cells[2].Value.ToString(); //订单份数 orderSorte.orderNum = this.goodDataGridView.Rows[i].Cells[3].Value == null ? "" : this.goodDataGridView.Rows[i].Cells[3].Value.ToString(); orderSorte.weight = weigth.ToString(); sorteDao sortedao = new sorteDao(); if (calFlag) { orderSorte.sorteNum = "1"; sortedao.AddtransitItem(orderSorte); } else { List <string> list = sortedao.FindBy(orderSorte.goods_id, weigth.ToString(), ConstantUtil.street); if (list.Count == 0) { voice.Speak("错误", speakflag); MessageBox.Show("没有此商品对应得分拣记录,无需进行减去操作", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); numberTextBox.Text = ""; return; } sortedao.DeleteBy(list[0]); calFlag = true; calculateButton.Text = "加(F1)"; } } numberTextBox.Text = ""; } else { } } if (!flag) { voice.Speak("错误", speakflag); MessageBox.Show("没有此商品,请确认商品或者货号是否正确", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning); numberTextBox.Text = ""; return; } }
/// <summary> /// Creates an audio representation of the current access code. /// </summary> /// <returns>A byte array of an PCM Wave audio form.</returns> public byte[] GenerateAudio() { #if MONO throw new NotImplementedException(); #else try { Random rnd = new Random(); string toSpeak = string.Empty; foreach (char c in AccessCode.ToCharArray()) { toSpeak += c.ToString() + ". "; } string tempPath = Path.GetTempPath(); if (!tempPath.EndsWith("\\")) { tempPath += "\\"; } string tempFile = tempPath + "sound" + Guid.NewGuid().ToString() + ".wav"; //we don't know why memorystream does not work. SpFileStream stream = null; try { stream = new SpFileStream(); stream.Open(tempFile, SpeechStreamFileMode.SSFMCreateForWrite, false); SpVoice speech = new SpVoice(); ISpeechObjectTokens voices = speech.GetVoices(string.Empty, string.Empty); if (voices == null) { throw new TenorException("No available voices."); } speech.Voice = voices.Item(rnd.Next(0, (int)voices.Count)); //Dim format As New SpAudioFormat //format.Type = SpeechAudioFormatType.SAFTGSM610_11kHzMono //sound.Format = format speech.AudioOutputStream = (ISpeechBaseStream)stream; speech.Rate = -2; //from -10 to +10 //speaks to the stream speech.Speak(toSpeak, SpeechVoiceSpeakFlags.SVSFlagsAsync); speech.WaitUntilDone(-1); speech = null; voices = null; } catch (Exception ex) { try { if (System.IO.File.Exists(tempFile)) { System.IO.File.Delete(tempFile); } } catch (Exception) { } throw ex; } finally { try { if (stream != null) { stream.Close(); } stream = null; } catch (Exception) { } } byte[] bytes = null; try { if (System.IO.File.Exists(tempFile)) { System.IO.FileStream file = new System.IO.FileStream(tempFile, System.IO.FileMode.Open); bytes = Tenor.IO.BinaryFile.StreamToBytes(file); file.Close(); System.IO.File.Delete(tempFile); } } catch { } return(bytes); } catch (Exception ex) { throw new TenorException("Cannot generate the audio tag. This server may not have the Ms Speech API.", ex); } #endif }
protected void Button1_Click(object sender, EventArgs e) { HyperLink1.Visible = false; SpVoice voice; voice = new SpVoice(); voice.Volume = 100; // 0...100 voice.Rate = -4; // -10...10 String s = Convert.ToString(txtuser.Text).Trim(); //white spaces removed String reply; s = s.ToLower(); string ans = "no"; if (s.Equals("hi") || s.Equals("hii") || s.Equals("hiii") || s.Equals("hiiii") || s.Equals("hhii") || s.Equals("hello") || s.Equals("helloo") || s.Equals("helo") || s.Equals("heello") || s.Equals("helllo") || s.Equals("helloooo")) { ans = "OK"; SqlDataAdapter da = new SqlDataAdapter("Select top 1 * from generalreply order by NEWID()", con); DataSet ds = new DataSet(); da.Fill(ds); reply = Convert.ToString(ds.Tables[0].Rows[0][1]); lblbot.Text = reply; voice.Speak(reply); } else if (s.Contains("i") && s.Contains("fine") || s.Contains("i") && s.Contains("good")) { ans = "OK"; SqlDataAdapter da = new SqlDataAdapter("Select top 1 * from addqueries order by NEWID()", con); DataSet ds = new DataSet(); da.Fill(ds); reply = Convert.ToString(ds.Tables[0].Rows[0][1]); lblbot.Text = reply; voice.Speak(reply); } //if (s.Contains("you") && s.Contains("how") || s.Contains("you") && s.Contains("how") && s.Contains("do")) //{ // ans = "OK"; // lblbot.Text = "I am Fine.. How Are You ?"; // voice.Speak("I am Fine.. How Are You ?"); //} else if (s.Contains("timetable")) { ans = "OK"; String s2, k1, k2, k3, rep = s; // s is not a string int count; SqlDataAdapter da4 = new SqlDataAdapter("Select * from timetable where keywords = '2'", con); DataSet ds4 = new DataSet(); da4.Fill(ds4); count = Convert.ToInt32(ds4.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds4.Tables[0].Rows[i][2]).ToLower(); k2 = Convert.ToString(ds4.Tables[0].Rows[i][3]).ToLower(); k3 = Convert.ToString(ds4.Tables[0].Rows[i][4]).ToLower(); if (s.Contains(k1) && s.Contains(k2)) { rep = Convert.ToString(ds4.Tables[0].Rows[i][7]); HyperLink1.Visible = true; HyperLink1.NavigateUrl = Convert.ToString(ds4.Tables[0].Rows[i][8]); voice.Speak(rep); } //-------------------- continue from here } if (rep == s) { da4 = new SqlDataAdapter("Select * from timetable where keywords = '2' order by newid()", con); ds4 = new DataSet(); da4.Fill(ds4); rep = Convert.ToString(ds4.Tables[0].Rows[0][7]); HyperLink1.Visible = true; HyperLink1.NavigateUrl = Convert.ToString(ds4.Tables[0].Rows[0][8]); voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("question papers") || s.Contains("question paper")) { ans = "OK"; String s2, k1, k2, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from QuestionPapers where keywords = '2'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); //reviews needed k2 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); if (s.Contains(k1) && s.Contains(k2)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][10]); HyperLink1.Visible = true; HyperLink1.NavigateUrl = Convert.ToString(ds3.Tables[0].Rows[i][11]); voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from QuestionPapers where keywords = '2' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]); HyperLink1.Visible = true; HyperLink1.NavigateUrl = Convert.ToString(ds3.Tables[0].Rows[0][8]); voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("reference book")) { ans = "OK"; String s2, k1, k2, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from ReferenceBook where keywords = '2'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); k2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); //k3 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); if (s.Contains(k1) && s.Contains(k2)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][7]);; voice.Speak(rep); break; } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from ReferenceBook where keywords = '2' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("subjects") || s.Contains("subject")) { ans = "OK"; String k1, k2, k3, k4, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from Subjects where keywords = '2'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); k2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); k3 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); k4 = Convert.ToString(ds3.Tables[0].Rows[i][5]).ToLower(); //k5 = Convert.ToString(ds3.Tables[0].Rows[i][5]).ToLower(); if (s.Contains(k1) && (s.Contains(k2) || s.Contains(k4)) && s.Contains(k3)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][9]); voice.Speak(rep); break; } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from Subjects where keywords = '2' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][9]); voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("cabin")) { ans = "OK"; String s2, k1, k2, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from Cabin where keywords = '2'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][1]).ToLower(); k2 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); if (s.Contains(k1) && s.Contains(k2)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][6]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from Cabin where keywords = '2' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][6]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("contact") || s.Contains("mobile")) { ans = "OK"; String s2, k1, k2, k3, k4, k5, k6, k7, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from Contact where keywords = '3'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); k2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); k3 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); k4 = Convert.ToString(ds3.Tables[0].Rows[i][5]).ToLower(); k5 = Convert.ToString(ds3.Tables[0].Rows[i][6]).ToLower(); // k6 = Convert.ToString(ds3.Tables[0].Rows[i][7]).ToLower(); // k7 = Convert.ToString(ds3.Tables[0].Rows[i][8]).ToLower(); if (s.Contains(k1) && s.Contains(k2) && s.Contains(k3) && s.Contains(k4) && s.Contains(k5)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][10]);; voice.Speak(rep); break; } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from Contact where keywords = '3' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][10]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("specialization") || s.Contains("specialization")) { ans = "OK"; String s2, k1, k2, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from specialization where keywords = '2'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); k2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); if (s.Contains(k1) && s.Contains(k2)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][7]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from specialization where keywords = '2' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("faculaties")) { ans = "OK"; String s2, k1, k2, k3, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from faculaties where keywords = '3'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); k2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); k3 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); if (s.Contains(k1) && s.Contains(k2) && s.Contains(k3)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][7]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from faculaties where keywords = '3' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("classroom")) { ans = "OK"; String s2, k1, k2, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from classroom where keywords = '2'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { k1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); k2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); if (s.Contains(k1) && s.Contains(k2)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][7]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from classroom where keywords = '2' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("how")) { ans = "OK"; String s2, query1, query2, query3, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from doublereply where keywords = '3'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { query1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); query2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); query3 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); if (s.Contains(query1) && s.Contains(query2) && s.Contains(query3)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][7]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from doublereply where keywords = '3' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("what")) { ans = "OK"; String s2, query1, query2, query3, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from whatdoublereply where keywords = '3'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { query1 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); query2 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); query3 = Convert.ToString(ds3.Tables[0].Rows[i][5]).ToLower(); if (s.Contains(query1) && s.Contains(query2) && s.Contains(query3)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][8]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from whatdoublereply where keywords = '3' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][8]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("where")) { ans = "OK"; String s2, query1, query2, query3, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from wheredoublereply where keywords = '3'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { query1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); query2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); query3 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); if (s.Contains(query1) && s.Contains(query2) && s.Contains(query3)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][7]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from wheredoublereply where keywords = '3' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]);; voice.Speak(rep); } lblbot.Text = rep; } else if (s.Contains("who")) { ans = "OK"; String s2, query1, query2, query3, rep = "s"; int count; SqlDataAdapter da3 = new SqlDataAdapter("Select * from whodoublereply where keywords = '3'", con); DataSet ds3 = new DataSet(); da3.Fill(ds3); count = Convert.ToInt32(ds3.Tables[0].Rows.Count); for (int i = 0; i < count; i++) { query1 = Convert.ToString(ds3.Tables[0].Rows[i][2]).ToLower(); query2 = Convert.ToString(ds3.Tables[0].Rows[i][3]).ToLower(); query3 = Convert.ToString(ds3.Tables[0].Rows[i][4]).ToLower(); if (s.Contains(query1) && s.Contains(query2) && s.Contains(query3)) { rep = Convert.ToString(ds3.Tables[0].Rows[i][7]);; voice.Speak(rep); } } if (rep == "s") { da3 = new SqlDataAdapter("Select * from whodoublereply where keywords = '3' order by newid()", con); ds3 = new DataSet(); da3.Fill(ds3); rep = Convert.ToString(ds3.Tables[0].Rows[0][7]);; voice.Speak(rep); } lblbot.Text = rep; } else if (ans != "OK") { string rep = Convert.ToString("No related Answer Found");; voice.Speak(rep); lblbot.Text = rep; } SqlCommand cmd = new SqlCommand("Insert into Ques(Question,Date,Time) values('" + txtuser.Text + "','" + DateTime.Now.ToShortDateString() + "','" + DateTime.Now.ToShortTimeString() + "')", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); speak_text.Text = null; txtuser.Text = ""; }
public void SpeechSelectionQuestion() //念出選擇題問題 { SpVoice speech = new SpVoice(); speech.Speak(_selectionQuestion.Question, SpeechVoiceSpeakFlags.SVSFlagsAsync); }
private void SpeakWithMicrosoftSpeechLibrary(string textToSpeak, Action onComplete, int?volume, int?rate, string voice) { var voiceToUse = voice ?? Settings.Default.SpeechVoice; if (!string.IsNullOrWhiteSpace(voiceToUse)) { if (!useLegacyMicrosoftSpeechForVoices.Contains(voiceToUse)) { try { speechSynthesiser.SelectVoice(voiceToUse); speechSynthesiser.Rate = rate ?? Settings.Default.SpeechRate; speechSynthesiser.Volume = volume ?? Settings.Default.SpeechVolume; } catch //(Exception exception) { //Commenting out the raising of an error notification for now //var customException = new ApplicationException(string.Format(Resources.UNABLE_TO_SET_VOICE_WARNING, // voiceToUse, voice == null ? Resources.VOICE_COMES_FROM_SETTINGS : null), exception); //PublishError(this, customException); Log.Warn($"Unable to speak using SpeechSynthesizer and voice '{voiceToUse}'. Switching to legacy speech mode and trying again..."); useLegacyMicrosoftSpeechForVoices.Add(voiceToUse); } } if (useLegacyMicrosoftSpeechForVoices.Contains(voiceToUse)) { Log.Info("Attempting speech using legacy mode."); try { if (legacySpeechSynthesiser == null) { //Lazy instantiate legacy speech synthesiser legacySpeechSynthesiser = new SpVoice(); } var availableVoices = legacySpeechSynthesiser.GetVoices(string.Empty, string.Empty); if (legacyMicrosoftSpeechVoiceToTokenIndexLookup.ContainsKey(voiceToUse)) { int voiceIndex = legacyMicrosoftSpeechVoiceToTokenIndexLookup[voiceToUse]; Log.InfoFormat($"{voiceToUse} voice token exists at index {voiceIndex}. Setting voice on legacy speech synthesiser."); legacySpeechSynthesiser.Voice = availableVoices.Item(voiceIndex); Log.Info("Voice token set."); } else { for (int voiceIndex = 0; voiceIndex < availableVoices.Count; voiceIndex++) { var voiceToken = availableVoices.Item(voiceIndex); if (voiceToken.GetDescription() == voiceToUse) { Log.InfoFormat($"{voiceToUse} voice token found at index {voiceIndex}. Setting voice on legacy speech synthesiser."); legacyMicrosoftSpeechVoiceToTokenIndexLookup.Add(voiceToUse, voiceIndex); legacySpeechSynthesiser.Voice = voiceToken; Log.Info("Voice token set."); break; } } } } catch (Exception exception) { var customException = new ApplicationException(string.Format(Resources.UNABLE_TO_SET_VOICE_WARNING, voiceToUse, voice == null ? Resources.VOICE_COMES_FROM_SETTINGS : null), exception); PublishError(this, customException); } } } //Speak if (!useLegacyMicrosoftSpeechForVoices.Contains(voiceToUse)) { onSpeakCompleted = (sender, args) => { lock (speakCompletedLock) { if (onSpeakCompleted != null) { speechSynthesiser.SpeakCompleted -= onSpeakCompleted; onSpeakCompleted = null; } if (onComplete != null) { onComplete(); } } }; speechSynthesiser.SpeakCompleted += onSpeakCompleted; speechSynthesiser.SpeakAsync(textToSpeak); } else { //Legacy speech mode if (legacySpeechSynthesiser != null) { legacySpeechSynthesiser.Speak(textToSpeak, SpeechVoiceSpeakFlags.SVSFIsNotXML | SpeechVoiceSpeakFlags.SVSFlagsAsync); var speechHandle = legacySpeechSynthesiser.SpeakCompleteEvent(); var speechHandlePtr = new IntPtr(speechHandle); if (speechHandlePtr != IntPtr.Zero) { var autoResetEvent = new AutoResetEvent(false) { SafeWaitHandle = new SafeWaitHandle(speechHandlePtr, false) }; var uiThreadDispatcher = Dispatcher.CurrentDispatcher; legacySpeakCompleted = (state, timedOut) => { if (onComplete != null) { uiThreadDispatcher.Invoke(onComplete); } autoResetEvent.Dispose(); legacySpeakCompleted = null; }; ThreadPool.RegisterWaitForSingleObject(autoResetEvent, legacySpeakCompleted, null, 30000, true); } } } }