/// <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();
			}
		}
Example #2
0
        /**
         * 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;
        }
Example #3
0
        private void speakToFile(Model.Wrapper wrapper, string outputFile)
        {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
            SpVoice speechSynthesizer = new SpVoice();

            SpFileStream spFile = new SpFileStream();

            spFile.Format.Type = SpeechAudioFormatType.SAFT48kHz16BitStereo;
            spFile.Open(outputFile, SpeechStreamFileMode.SSFMCreateForWrite);

            SpObjectToken voice = getSapiVoice(wrapper.Voice);

            if (voice != null)
            {
                speechSynthesizer.Voice = voice;
            }

            speechSynthesizer.AudioOutputStream = spFile;
            speechSynthesizer.Volume            = calculateVolume(wrapper.Volume);
            speechSynthesizer.Rate = calculateRate(wrapper.Rate);
            speechSynthesizer.Speak(prepareText(wrapper), wrapper.ForceSSML && !Speaker.isAutoClearTags ? SpeechVoiceSpeakFlags.SVSFIsXML : SpeechVoiceSpeakFlags.SVSFIsNotXML);

            speechSynthesizer.WaitUntilDone(int.MaxValue);

            spFile.Close();
#endif
        }
Example #4
0
        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
            {

            }
        }
    // Function for converting text to a voiced wav file via text-to-speech
    public bool TextToWav(string FilePath, string text)
    {
        //VA.WriteToLog("creating wav file"); // Output info to event log
        SpFileStream stream = new SpFileStream();                                 // Create new SpFileStream instance

        try                                                                       // Attempt the following code
        {
            if (System.IO.File.Exists(FilePath) == true)                          // Check if voice recognition wav file already exists
            {
                System.IO.File.Delete(FilePath);                                  // Delete existing voice recognition wav file
            }
            stream.Format.Type = SpeechAudioFormatType.SAFT48kHz16BitStereo;      // Set the file stream audio format
            stream.Open(FilePath, SpeechStreamFileMode.SSFMCreateForWrite, true); // Open the specified file for writing with events enabled
            SpVoice voice = new SpVoice();                                        // Create new SPVoice instance
            voice.Volume = 100;                                                   // Set the volume level of the text-to-speech voice
            voice.Rate   = -2;                                                    // Set the rate at which text is spoken by the text-to-speech engine
            string NameAttribute = "Name = " + VA.GetText("~~TextToSpeechVoice");
            voice.Voice = voice.GetVoices(NameAttribute).Item(0);
            //voice.Speak(text);
            voice.AudioOutputStream = stream;                                          // Send the audio output to the file stream
            voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault);                      // Internally "speak" the inputted text (which records it in the wav file)
            voice = null;                                                              // Set to null in preparation for garbage collection
        }
        catch                                                                          // Handle exceptions in above code
        {
            VA.SetText("~~RecognitionError", "Error during wav file creation (SAPI)"); // Send error detail back to VoiceAttack as text variable
            return(false);                                                             // Send "false" back to calling code line
        }
        finally                                                                        // Runs whether an exception is encountered or not
        {
            stream.Close();                                                            // Close the file stream
            stream = null;                                                             // Set to null in preparation for garbage collection
        }
        return(true);                                                                  // Send "true" back to calling code line
    }
Example #6
0
        /// <summary>
        /// 生成音频文件
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="mSpeakFlags"></param>
        public string ExportFile(SpeechVoiceSpeakFlags mSpeakFlags)
        {
            SpFileStream SpFileStream = null;

            try
            {
                SpFileStream = new SpFileStream();
                string fileName = DateTime.Now.Ticks.ToString();
                SpFileStream.Open(AppDomain.CurrentDomain.BaseDirectory + @"\wav\" + fileName + ".wav", SpeechStreamFileMode.SSFMCreateForWrite, false);
                mSpVoiceClass.AudioOutputStream = SpFileStream;
                this.Speak(mSpeakFlags);
                mSpVoiceClass.WaitUntilDone(-1);
                mSpVoiceClass.AudioOutputStream = null;   //必需置空,否则后面无法发音
                return(fileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (SpFileStream != null)
                {
                    SpFileStream.Close();
                }
            }
        }
Example #7
0
        public void Save(string filePath, string text)
        {
            try
            {
                SpObjectToken backupSapi = null;
                SpFileStream  ss         = new SpFileStream();
                ss.Open(filePath, SpeechStreamFileMode.SSFMCreateForWrite);
                sapi.AudioOutputStream = ss;

                Thread t = new Thread(() => {
                    backupSapi  = sapi.Voice;
                    sapi.Voice  = SpeakerList[AvatorIdx];
                    sapi.Rate   = Speed;
                    sapi.Volume = Volume;
                    sapi.Speak(text);
                    sapi.Voice = backupSapi;
                });
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
                t.Join();
                ss.Close();
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("保存処理で落ちたっす。{0}", e.Message));
            }
        }
Example #8
0
 private void buttonX2_Click(object sender, EventArgs e)
 {
     try
     {
         SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFDefault;
         SpVoice        Voice          = new SpVoice();
         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(textspeechText.Text, SpFlags);
             Voice.WaitUntilDone(1000);
             SpFileStream.Close();
         }
     }
     catch (Exception er)
     {
         //MessageBox.Show("An Error Occured!", "SpeechApp", MessageBoxButtons.OK, MessageBoxIcon.Error);
         System.Console.WriteLine(er.ToString());
     }
 }
 public void PlaySound(string soundFilename)
 {
     SpFileStream fs = new SpFileStream(); // File stream for loading wav file
     try
     {
         if (fs != null)
         {
             // Use SVSFDefault to make sure speech play the wav file
             fs.Open(soundFilename, SpeechStreamFileMode.SSFMOpenForRead, false);
             speech.SpeakStream(fs, SpeechVoiceSpeakFlags.SVSFDefault);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Exception!\n" + ex.Message + "\n" + ex.StackTrace);
     }
     finally
     {
         // Make sure file stream close
         if (fs != null)
         {
             fs.Close();
         }
     }
 }
Example #10
0
 /// <summary>
 /// Fala em arquivo wave
 /// </summary>
 /// <param name="Text"></param>
 /// <param name="FileName"></param>
 public void SpeakToWave(string Text, string FileName)
 {
     SpFileStream.Open(FileName, SpeechStreamFileMode.SSFMCreateForWrite, false);
     vox.AudioOutputStream = SpFileStream;
     vox.Speak(Text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
     vox.WaitUntilDone(-1);
     SpFileStream.Close();
 }
Example #11
0
 public Speech()
 {
     vox          = new SpVoice();
     SpFileStream = new SpFileStream();
     voiceList    = new List <string>();
     idx          = -1;
     setVoices();
 }
Example #12
0
        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;
        }
        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;
        }
Example #14
0
        /// <summary>
        /// Set up a file stream by path.
        /// </summary>
        private static SpFileStream PrepareFileStreamToWrite(string path)
        {
            SpFileStream  stream = new SpFileStream();
            SpAudioFormat format = new SpAudioFormat();

            format.Type   = SpeechAudioFormatType.SAFT48kHz16BitMono;
            stream.Format = format;
            stream.Open(path, SpeechStreamFileMode.SSFMCreateForWrite, true);

            return(stream);
        }
Example #15
0
    void TestAudio(string text)
    {
        SpVoice      voice = new SpVoice();
        SpFileStream sfs   = new SpFileStream();

        sfs.Open("c:\\1.wav", SpeechStreamFileMode.SSFMCreateForWrite, false);
        voice.AudioOutputStream = sfs;
        voice.Speak(text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        voice.WaitUntilDone(1000);
        sfs.Close();
    }
Example #16
0
        public void CreatePromt(string Text, string FileName)
        {
            voice.Volume = 100;
            voice.Rate   = 0;
            SpFileStream fs   = new SpFileStream();
            string       path = Application.dataPath + "/Resources/Sounds/" + FileName + ".wav";

            fs.Open(path, SpeechStreamFileMode.SSFMCreateForWrite, false);
            voice.AudioOutputStream = fs;
            voice.Speak(Text, SpeechVoiceSpeakFlags.SVSFDefault);
            fs.Close();
        }
Example #17
0
 //文字转语音录频
 private void btnSpeak_Click(object sender, EventArgs e)
 {
     SpFileStream stream = new SpFileStream();
     stream.Open(@"C:\Users\tom86\Desktop\voice.wav", SpeechStreamFileMode.SSFMCreateForWrite, false);
     SpVoice voice = new SpVoice();
     voice.AudioOutputStream = stream;
     //voice.Rate = 1;//语速
     voice.Speak(comboBox5.Text);
     voice.WaitUntilDone(Timeout.Infinite);
     stream.Close();
     MessageBox.Show("转换音频文件成功");
 }
Example #18
0
 ///<summary>SpVoiceSpeak</summary>
 public static void SpVoiceSpeak
 (
  ref UtilitySpeechArgument  utilitySpeechArgument,
  ref string                 exceptionMessage
 )
 {
  object                 voice                  =  null;
  object[]               voiceArgv              =  null;                  
  SpeechVoiceSpeakFlags  speechVoiceSpeakFlags  =  SpeechVoiceSpeakFlagsDefault;
  SpAudioFormatClass     spAudioFormatClass     =  null;
  SpFileStream           spFileStream           =  null;
  SpVoice                spVoice                =  null;
  Type                   typeSAPISpVoice        =  null;
  try
  {
   spVoice                =  new SpVoice();
   typeSAPISpVoice        =  Type.GetTypeFromProgID("SAPI.SpVoice");
   voice                  =  Activator.CreateInstance( typeSAPISpVoice );
   voiceArgv              =  new object[2];
   voiceArgv[1]           =  0;
   speechVoiceSpeakFlags  =  SpeechVoiceSpeakFlagsEnum( false, utilitySpeechArgument.xml );
   if ( string.IsNullOrEmpty( utilitySpeechArgument.pathAudio ) == false )
   {
    spAudioFormatClass         =  new SpAudioFormatClass();
    spAudioFormatClass.Type    =  SpeechAudioFormatType.SAFTGSM610_11kHzMono; //Heavily compressed
    spFileStream               =  new SpFileStream();
    spFileStream.Format        =  spAudioFormatClass;
    spFileStream.Open( utilitySpeechArgument.pathAudio, SpeechStreamFileMode.SSFMCreateForWrite, false );
    spVoice.AudioOutputStream  =  spFileStream;
    spVoice.Rate = -5; //Ranges from -10 to 10 
   }
   foreach( string text in utilitySpeechArgument.text )
   {
    /*
    spVoice.Speak( text, speechVoiceSpeakFlags );
    */
    voiceArgv[0]  =  text;
    typeSAPISpVoice.InvokeMember("Speak", BindingFlags.InvokeMethod, null, voice, voiceArgv);
   }
   speechVoiceSpeakFlags = SpeechVoiceSpeakFlagsEnum( true, utilitySpeechArgument.xml );
   foreach( string pathSource in utilitySpeechArgument.pathSource )
   {
    if ( string.IsNullOrEmpty( pathSource ) ) { continue; }
    if ( File.Exists( pathSource ) == false ) { continue; }     
    spVoice.Speak( pathSource, speechVoiceSpeakFlags );
   }//foreach( string pathSource in utilitySpeechArgument.pathSource )
  }//try
  catch ( Exception exception ) { UtilityException.ExceptionLog( exception, exception.GetType().Name, ref exceptionMessage ); }
  if ( spFileStream != null ) { spFileStream.Close(); }
 }//public static void SpVoiceSpeak()
Example #19
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SpVoice      oVoice       = new SpVoice();
                SpFileStream cpFileStream = new SpFileStream();

                cpFileStream.Open(SaveFileDialog1.FileName, SpeechLib.SpeechStreamFileMode.SSFMCreateForWrite, false);
                SpeechAudioFormatInfo info  = new SpeechAudioFormatInfo(6, AudioBitsPerSample.Sixteen, AudioChannel.Mono);
                SpAudioFormat         info1 = new SpAudioFormat();

                info1.Type = SpeechAudioFormatType.SAFTGSM610_11kHzMono;
                cpFileStream.Format.Type = SpeechAudioFormatType.SAFT11kHz16BitStereo;


                oVoice.AudioOutputStream = cpFileStream;
                oVoice.Voice             = oVoice.GetVoices().Item(cboVoice.SelectedIndex);
                oVoice.Volume            = trVolume.Value;
                oVoice.Rate = trRate.Value;
                oVoice.Speak(txtSpeak.Text, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);

                oVoice = null;
                cpFileStream.Close();
                cpFileStream = null;
            }

            //SpFileStream spFileStream = new SpFileStream();



            //SpVoice speech = new SpVoice();



            //SpAudioFormat format = new SpAudioFormat();


            //spFileStream.Open(@"d:\dude.wav", SpeechStreamFileMode.SSFMCreateForWrite, true);

            //speech.AudioOutputStream = spFileStream;


            ////NOTE: This is where I get hosed
            //speech.Voice = speech.GetVoices().Item(0);
            //speech.Volume = trVolume.Value;
            //speech.Rate = trRate.Value;
            //speech.Speak("I love you", SpeechVoiceSpeakFlags.SVSFDefault);
            //spFileStream.Close();
            //spFileStream = null;
        }
Example #20
0
        private void btnSpeak_Click(object sender, System.EventArgs e)
        {
            if ((Convert.ToInt32(btnSpeak.Tag) == 0) && (sender != null))
            {
                btnSpeak.Tag  = 1;
                btnSpeak.Text = "STOP";

                try
                {
                    if (cbVoices.Text.Length > 0)
                    {
                        m_voice.Voice = m_voice.GetVoices(string.Format("Name={0}", cbVoices.Text), "Language=409").Item(0);
                    }

                    if (cbSaveToWave.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);
                            m_voice.AudioOutputStream = SpFileStream;
                            m_voice.Speak(textBox1.Text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
                            m_voice.WaitUntilDone(Timeout.Infinite);
                            SpFileStream.Close();
                        }
                    }
                    else
                    {
                        m_voice.Speak(textBox1.Text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
                    }
                }
                catch
                {
                    MessageBox.Show("Speak error");
                }
            }
            else
            {
                btnSpeak.Tag  = 0;
                btnSpeak.Text = "SPEAK";
                m_voice.Speak(null, (SpeechVoiceSpeakFlags)2);
                m_voice.Resume();
            }
        }
Example #21
0
        private void btnTalk_Click(object sender, EventArgs e)
        {
            SpVoice      oVoice       = new SpVoice();
            SpFileStream cpFileStream = new SpFileStream();

            oVoice.Voice  = oVoice.GetVoices().Item(1);
            oVoice.Volume = trVolume.Value;
            oVoice.Rate   = trRate.Value;//4

            string speak = txtSentence.Text.Replace(" x ", " " + txtX.Text + " ");

            speak = speak.Replace(" y", " " + txtY.Text);
            oVoice.Speak(speak, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);
        }
Example #22
0
 public bool SaveAsWAV(string path, string str, SpeechAudioFormatType SpAudioType)
 {
     SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
     SpFileStream SpFileStream = new SpFileStream();
     SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
     SpAudioFormat SpAudio = new SpAudioFormat();
     SpAudio.Type = SpAudioType;
     SpFileStream.Format = SpAudio;
     SpFileStream.Open(path, SpFileMode, false);
     mVoice.AudioOutputStream = SpFileStream;
     mVoice.Speak(str, SpFlags);
     mVoice.WaitUntilDone(Timeout.Infinite);
     SpFileStream.Close();
     return File.Exists(path);
 }
Example #23
0
        public void txtToFile(string value, string fileName)
        {
            GC.Collect();
            SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;

            SpeechLib.SpVoice    voice        = new SpVoiceClass();
            SpeechStreamFileMode SpFileMode   = SpeechStreamFileMode.SSFMCreateForWrite;
            SpFileStream         SpFileStream = new SpFileStream();

            SpFileStream.Open(fileName, SpFileMode, false);
            voice.AudioOutputStream = SpFileStream;
            voice.Speak(value, SpFlags);
            voice.WaitUntilDone(System.Threading.Timeout.Infinite);
            SpFileStream.Close();
        }
    private void convertAndSaveDialog(EventGate speechObject)
    {
        string fileName = "";

        if (speechObject.gameObject.GetComponent <EventHandler>() != null)
        {
            fileName = speechObject.gameObject.name;
        }
        else
        {
            fileName = speechObject.transform.parent.name;
        }
        var pathEnglish = EditorUtility.SaveFilePanel(
            "Save english speech as WAV",
            Application.dataPath,
            fileName + "-English.wav",
            "wav");
        SpFileStream SpFileStreamEnglish = new SpFileStream();

        SpFileStreamEnglish.Open(pathEnglish, speechFileMode, false);
        voice.AudioOutputStream = SpFileStreamEnglish;
        voice.Voice             = tokens.Item(EnglishLanguageIndex);
        voice.Speak(speechObject.AVASEnglishText, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        voice.WaitUntilDone(Timeout.Infinite);//Using System.Threading;
        SpFileStreamEnglish.Close();
        AudioClip speechEnglishAudio = (AudioClip)Resources.Load(pathEnglish);

        speechObject.AVASEnglishAudio = speechEnglishAudio;
        ShowNotification(new GUIContent("Conversion of English Text is done!"), 2);

        var pathGerman = EditorUtility.SaveFilePanel(
            "Save english speech as WAV",
            Application.dataPath,
            fileName + "-German.wav",
            "wav");
        SpFileStream SpFileStreamGerman = new SpFileStream();

        SpFileStreamGerman.Open(pathGerman, speechFileMode, false);
        voice.AudioOutputStream = SpFileStreamGerman;
        voice.Voice             = tokens.Item(GermanLanguageIndex);
        voice.Speak(speechObject.AVASGermanText, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        voice.WaitUntilDone(Timeout.Infinite);//Using System.Threading;
        SpFileStreamGerman.Close();
        AudioClip speechGermanAudio = (AudioClip)Resources.Load(pathGerman);

        speechObject.AVASEnglishAudio = speechGermanAudio;
        ShowNotification(new GUIContent("Conversion of German Text is done!"), 2);
    }
Example #25
0
        public void suaraToFile(string kata, string fname)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            voice = ConfVoice();

            SpeechStreamFileMode spFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
            SpFileStream         spFs       = new SpFileStream();

            spFs.Open(path + "/" + fname + ".wav", spFileMode, false);
            voice.AudioOutputStream = spFs;
            voice.Speak(kata, SpeechVoiceSpeakFlags.SVSFlagsAsync);
            voice.WaitUntilDone(Timeout.Infinite);
            spFs.Close();
        }
    private void convertAndSaveDialog(string speechToConvert)
    {
        var path = EditorUtility.SaveFilePanel(
            "Save speech as WAV",
            "",
            "converted speech" + ".wav",
            "wav");
        SpFileStream SpFileStream = new SpFileStream();

        SpFileStream.Open(path, speechFileMode, false);
        voice.AudioOutputStream = SpFileStream;
        voice.Speak(speechToConvert, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        voice.WaitUntilDone(50000);//Using System.Threading;
        ShowNotification(new GUIContent("Conversion is done! \n you can find your file at: " + path));

        SpFileStream.Close();
    }
Example #27
0
 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;
 }
Example #28
0
        public void SayInFile(int voiceNum, string input)
        {
            try
            {
                SpFileStream SPFileStream = new SpFileStream();
                SPFileStream.Open(tempFolder + "output.wav", SpeechStreamFileMode.SSFMCreateForWrite, false);
                //               SPFileStream.Open("output.wav", SpeechStreamFileMode.SSFMCreateForWrite, false);

                FileWriteVoice.AudioOutputStream = SPFileStream;
                FileWriteVoice.Voice             = voice.GetVoices("gender=female").Item(voiceNum);
                FileWriteVoice.Speak(input);
                SPFileStream.Close();
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }
Example #29
0
        public static string SpeekToFile(string word)
        {
            string url;

            if (!CheckWord(word, out url))
            {
                var path  = Utils.GetCurrentDir() + 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);
        }
Example #30
0
        // 导出音频文件
        private void btnExportFile_Click(object sender, RoutedEventArgs e)
        {
            this.btnExportFile.IsEnabled = false;
            string path = AppDomain.CurrentDomain.BaseDirectory;

            if (System.IO.Directory.Exists(path + "Sounds"))
            {
                string[] files = System.IO.Directory.GetFiles(path + "Sounds");
                foreach (string file in files)
                {
                    try
                    {
                        System.IO.File.Delete(file);
                    }
                    catch (System.Exception ex)
                    {
                    }
                }
            }
            else
            {
                System.IO.Directory.CreateDirectory(path + "Sounds");
            }

            SpFileStream filestream = new SpFileStream();

            this.progressBar.Visibility = System.Windows.Visibility.Visible;
            this.progressBar.Maximum    = dc.Student.Count();
            this.progressBar.Value      = 0;
            foreach (Codes.Student student in dc.Student.ToList())
            {
                // wpf中没有DoEvents()不过幸好一个外国人帮忙写了类似的函数
                App.DoEvents();
                filestream.Open(path + "Sounds\\" + student.No + student.Name + ".wav", SpeechStreamFileMode.SSFMCreateForWrite, false);
                voice.AudioOutputStream = filestream;
                voice.Speak(student.Name.Trim(), SpeechVoiceSpeakFlags.SVSFlagsAsync);
                voice.WaitUntilDone(1000);
                filestream.Close();
                this.progressBar.Value++;
            }
            this.progressBar.Visibility  = System.Windows.Visibility.Hidden;
            this.btnExportFile.IsEnabled = true;
            MessageBox.Show("音频文件导出成功", "操作提示", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            SaveFileDialog file = new SaveFileDialog();

            file.Title       = "保存音频文件";
            file.Filter      = "音频文件|*.wav";
            file.FilterIndex = 1;
            if (file.ShowDialog() == true)
            {
                SpFileStream spFileStream = new SpFileStream();
                spFileStream.Format.Type = SpeechAudioFormatType.SAFT16kHz16BitMono;
                spFileStream.Open(file.FileName, SpeechStreamFileMode.SSFMCreateForWrite, false);
                sp.AudioOutputStream = spFileStream;
                sp.Speak(pitch + Text2Talk.Text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
                sp.WaitUntilDone(-1);
                sp.AudioOutputStream = null;
                spFileStream.Close();
            }
        }
Example #32
0
        /// <summary>
        /// 开始转换
        /// </summary>
        public void Convert()
        {
            SpFileStream  sr    = new SpFileStream();
            SpAudioFormat audio = new SpAudioFormat();

            audio.Type = Format;
            sr.Format  = audio;
            sr.Open(SaveFileName, SpeechStreamFileMode.SSFMCreateForWrite, false);

            SpVoice voice = new SpVoice();

            voice.Voice             = voice.GetVoices(null, null).Item(0);//语言设置
            voice.Rate              = Rate;
            voice.AudioOutputStream = sr;
            voice.Volume            = Volume == 0 ? 100 : Volume;
            voice.Speak(InputText, SpeechVoiceSpeakFlags.SVSFlagsAsync);
            voice.WaitUntilDone(Timeout.Infinite);
            sr.Close();
        }
    public override void Initialize(TextToSpeechOptions ttsOptions)
    {
        if (ttsOptions.GetType() == typeof(SpeechLibTTSOptions))
        {
            windowsTTSOptions = (SpeechLibTTSOptions)ttsOptions;

            SpObjectTokenCategory tokenCat = new SpObjectTokenCategory();
            tokenCat.SetId(SpeechLib.SpeechStringConstants.SpeechCategoryVoices, false);
            ISpeechObjectTokens tokens = tokenCat.EnumerateTokens(null, null);

            spVoice = new SpVoice();

            spVoice.Voice  = tokens.Item(windowsTTSOptions.Voice);
            spVoice.Volume = windowsTTSOptions.Volume;
            spVoice.Rate   = windowsTTSOptions.Rate;

            spFileStream = new SpFileStream();
        }
    }
Example #34
0
        private void btnSpeak_Click(object sender, EventArgs e)
        {
            if (cboVoice.SelectedIndex == -1)
            {
                return;
            }
            SpVoice      oVoice       = new SpVoice();
            SpFileStream cpFileStream = new SpFileStream();

            oVoice.Voice  = oVoice.GetVoices().Item(cboVoice.SelectedIndex);
            oVoice.Volume = trVolume.Value;
            oVoice.Rate   = trRate.Value;
            oVoice.Speak(txtSpeak.Text, SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);
            ////SpeechSynthesizer s = new SpeechSynthesizer();
            //SpVoice s = new SpVoice();
            //s.Speak("my name is Phu");
            ////s.Speak("Hello. My name is Microsoft Server Speech Text to Speech Voice (en-US, Helen).");
            //ISpeechRecoContext catchText = new SpInProcRecoContext();
        }
        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;
            }
        }
Example #36
0
        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);
        }
    public byte[] TextToSpeak(string text)
    {
        string       filename = "temp.wav";
        SpFileStream objFSTRM = new SpFileStream();

        objFSTRM.Open(filename, SpeechStreamFileMode.SSFMCreateForWrite, false);
        SpVoice objVoice = new SpVoice();

        objVoice.AudioOutputStream = objFSTRM;
        objVoice.Volume            = 100;
        objVoice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault);
        objFSTRM.Close();
        objVoice.AudioOutputStream = null;
        // Doc file de chuyen di
        FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);

        byte[] kq = new byte[fs.Length];
        fs.Read(kq, 0, kq.Length);
        fs.Close();
        return(kq);
    }
        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;
        }
Example #39
0
        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);
                    }
               }

            }
        }
 public void export(string message, string file)
 {
     SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
     SpFileStream SpFileStream = new SpFileStream();
     SpFileStream.Open(file, SpFileMode, false);
     _exportVoice.AudioOutputStream = SpFileStream;
     _exportVoice.Volume = settings.volume;
     _exportVoice.Rate = settings.speed;
     string voiceIdString = settings.voice;
     if (voiceIdString != String.Empty)
     {
         ISpeechObjectTokens sot = _exportVoice.GetVoices("", "");
         string[] voiceIds = new string[sot.Count];
         for (int i = 0; i < sot.Count; i++)
         {
             voiceIds[i] = sot.Item(i).GetDescription(1033);
             if (voiceIds[i] == voiceIdString)
                 _exportVoice.Voice = sot.Item(i);
         }
     }
     _exportVoice.Speak(message, SpeechVoiceSpeakFlags.SVSFDefault);
     //_voice.Speak(message, SpeechVoiceSpeakFlags.SVSFDefault);
     SpFileStream.Close();
 }
 public void SayItToFile(int languageIndex, int rate, string textToSay, string filenameOut)
 {
     Vox.Voice = Vox.GetVoices().Item(languageIndex);
     Vox.Rate = rate;
     try
     {
         var options = SpeechVoiceSpeakFlags.SVSFlagsAsync;
         var stream = new SpFileStream();
         stream.Open(filenameOut, SpeechStreamFileMode.SSFMCreateForWrite, true);
         Vox.AudioOutputStream = stream;
         Vox.Speak(textToSay, options);
         Vox.WaitUntilDone(100000);
         stream.Close();
         Vox.AudioOutputStream = null;
     }
     catch (Exception ex) { }
 }
        private bool fnSpeakToWav(string strWordToSpeak, string strPathToSave)
        {
            string aaa = strPathToSave.Substring(0, strPathToSave.LastIndexOf(@"\") + 1);

            try
            {
                //Ensure that the target'directory is exis
                if (Directory.Exists(strPathToSave.Substring(0, strPathToSave.LastIndexOf(@"\") + 1)) == false)
                    Directory.CreateDirectory(strPathToSave.Substring(0, strPathToSave.LastIndexOf(@"\") + 1));
            }
            catch (Exception)
            { }

            try
            {	//Ensure that the target does not exist.
                if (File.Exists(strPathToSave) == true)
                    File.Delete(strPathToSave);
            }
            catch (Exception)
            { }

            //speak
            try
            {
                V.Voice = V.GetVoices().Item(intPPATatipNumber);

                //Set output stream to speaker
                V.AllowAudioOutputFormatChangesOnNextSet = true;
                //V.AudioOutputStream = null;  //migrate to vmware (no audio device)
                //AUTO-GENERATE
                //Change TTS for book name

                //create a wave stream
                SpFileStream cpFileStream = new SpFileStream();
                cpFileStream.Format.Type = SpeechAudioFormatType.SAFT11kHz8BitMono;

                //Generate Book Name
                cpFileStream.Open(strPathToSave, SpeechStreamFileMode.SSFMCreateForWrite, false);
                //Set output stream to the file stream
                V.AllowAudioOutputFormatChangesOnNextSet = false;
                V.AudioOutputStream = cpFileStream;
                //speak the given text with given flags
                V.Speak(strWordToSpeak, SpeechVoiceSpeakFlags.SVSFDefault);
                //wait until it's done speaking with a really really long timeout.
                //the tiemout value is in unit of millisecond. -1 means forever.
                V.WaitUntilDone(-1);
                //close the file stream
                cpFileStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"There is an error while converting The book Title and detail to WAV files. " + ex.Message, @"fnSpeakToWav");
                return false;
            }

            //Check Size
            System.IO.FileInfo currentfileInfo = new System.IO.FileInfo(strPathToSave);

            if (currentfileInfo.Length > 0)
                return true;
            else
                return false;
        }
        private bool fnAutoUploadNews(string strNcxPath, string strDestinationOfAutoNewsPath, string strCatalogCode, string strBookTitle, string strBookDetail)
        {
            int intBookId = 1;
            try
            {
                myConn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strDestinationOfAutoNewsPath + @"Books.mdb");
                myConn.Open();
                //Looking for the last(less) book ID
                OleDbCommand myCmd = new OleDbCommand(@"Select BookID from TbBookInfo where CategoryCode like '" + strCatalogCode.Trim() + @"' order by BookID asc", myConn);
                myReader = myCmd.ExecuteReader();
                if (myReader.HasRows == true)
                {
                    while (myReader.Read())
                    {
                        if (intBookId == int.Parse(myReader[0].ToString()))
                        {
                            intBookId++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    //return false;
                    intBookId = 1;
                }

                myConn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error in fnAutoUploadNews");
                myConn.Close();
                return false;

            }

            string strBookId = intBookId.ToString("0000").Trim();
            string strBookNameFilePath = strDestinationOfAutoNewsPath + @"bookPrompts\" + strCatalogCode + strBookId + @"p.wav";
            string strBookDetailFilePath = strDestinationOfAutoNewsPath + @"bookPrompts\" + strCatalogCode + strBookId + @"d.wav";

            try
            {	//Ensure that the target does not exist.
                if (File.Exists(strBookNameFilePath) == true)
                    File.Delete(strBookNameFilePath);
            }
            catch (Exception)
            { }

            try
            {	//Ensure that the target does not exist.
                if (File.Exists(strBookDetailFilePath) == true)
                    File.Delete(strBookDetailFilePath);
            }
            catch (Exception)
            { }

            try
            {
                V.Voice = V.GetVoices().Item(intPPATatipNumber);

                //Set output stream to speaker
                V.AllowAudioOutputFormatChangesOnNextSet = true;
                V.AudioOutputStream = null;
                //AUTO-GENERATE
                //Change TTS for book name

                //create a wave stream
                SpFileStream cpFileStream = new SpFileStream();
                cpFileStream.Format.Type = SpeechAudioFormatType.SAFT11kHz8BitMono;

                //Generate Book Name
                cpFileStream.Open(strBookNameFilePath, SpeechStreamFileMode.SSFMCreateForWrite, false);
                //Set output stream to the file stream
                V.AllowAudioOutputFormatChangesOnNextSet = false;
                V.AudioOutputStream = cpFileStream;
                //speak the given text with given flags
                V.Speak(strBookTitle, SpeechVoiceSpeakFlags.SVSFDefault);
                //wait until it's done speaking with a really really long timeout.
                //the tiemout value is in unit of millisecond. -1 means forever.
                V.WaitUntilDone(-1);
                //close the file stream
                cpFileStream.Close();

                //Generate Book Detail
                cpFileStream.Open(strBookDetailFilePath, SpeechStreamFileMode.SSFMCreateForWrite, false);
                //Set output stream to the file stream
                V.AllowAudioOutputFormatChangesOnNextSet = false;
                V.AudioOutputStream = cpFileStream;
                //speak the given text with given flags
                V.Speak(strBookDetail, SpeechVoiceSpeakFlags.SVSFDefault);
                //wait until it's done speaking with a really really long timeout.
                //the tiemout value is in unit of millisecond. -1 means forever.
                V.WaitUntilDone(-1);
                //close the file stream
                cpFileStream.Close();
                cpFileStream = null;
            }
            catch (Exception)
            {
                MessageBox.Show(@"There is an error while converting The book Title and detail to WAV files.", @"fnAutoUploadNews");
                return false;
            }

            ///////////////////////////////////////////////////////
            //update database (delete old & add new) for bookName//
            ///////////////////////////////////////////////////////
            try
            {
                myConn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strDestinationOfAutoNewsPath + @"Books.mdb");
                myConn.Open();

                myCmd = new OleDbCommand(@"delete from TbBookInfo where CategoryCode like '" + strCatalogCode + @"' and BookID like '" + strBookId + @"'", myConn);
                myCmd.ExecuteNonQuery();

                string tmpList = @"insert into TbBookInfo(9DigitBookCode,BookID,BookName,CategoryCode,BookDetail,SortOrder) values('" + strCatalogCode + strBookId + @"','" + strBookId + @"','" + strBookTitle.Trim() + @"','" + strCatalogCode + @"','" + strBookDetail.Trim() + @"','" + strBookId.Trim() + @"')";
                myCmd = new OleDbCommand(tmpList, myConn);
                myCmd.ExecuteNonQuery();

                myConn.Close();
            }
            catch (Exception ex)
            {
                myConn.Close();
                MessageBox.Show(@"There is an error while inserting DTBs record to the book.mdb. " + ex.Message, @"Error in fnAutoUploadNews");
                return false;
            }

            //ระบุ Directory ต้นทาง และ ปลายทาง
            string strSourceDirectory = strNcxPath.Substring(0, strNcxPath.Length - 7);

            string strDestinationDirectory = strDestinationOfAutoNewsPath + @"Library\" + strCatalogCode + @"\" + strBookId + @"\";

            if (strSourceDirectory != "")
            {
                try
                {
                    //Deltree สำหรับ Directory ปลายทาง
                    Directory.Delete(strDestinationDirectory, true);
                }
                catch (Exception)
                { }

                try
                {
                    //สร้าง Directory ปลายทาง
                    Directory.CreateDirectory(strDestinationDirectory);
                    //คัดลอกไปยัง Directory ปลายทาง
                    string[] f = Directory.GetFiles(strSourceDirectory);
                    foreach (string s in f)
                    {
                        File.Copy(s, strDestinationDirectory + fnGetFileNameWithoutThePath(s));
                    }
                    //DONE
                }
                catch (Exception)
                {
                    MessageBox.Show(@"There is an error while copying NEWS to the destination.", @"fnAutoUploadNews");
                    return false;
                }
            }
            return true;
        }
        void keyboardHook_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Only process the key press event whenthe it is in Practice state
            if (false == skipKeyPress && States.Practice == currentState)
            {
                //display text that was typed
                textBox1.Text = e.KeyChar.ToString() + textBox1.Text;
                textBox1.Refresh();

                SpFileStream fs = new SpFileStream(); // File stream for loading wav file

                try
                {
                    // Speak the key character that is pressed
                    string curKeyCode = e.KeyChar.ToString();
                    switch (curKeyCode)
                    {
                        case ",":
                            speech.Speak("逗号", spFlagsAsynPurge);
                            break;
                        case ".":
                            speech.Speak("句号", spFlagsAsynPurge);
                            break;
                        case ";":
                            speech.Speak("分号", spFlagsAsynPurge);
                            break;
                        default:
                            speech.Speak(PinYinSpeechConverter.Convert(e.KeyChar.ToString()), spFlagsAsynPurge);
                            break;
                    }

                    // Correct!
                    if (e.KeyChar.ToString().ToLower() == ((LessonScreen)screenArray[screenIndex]).toType)
                    {
                        // Play a sound to indicate corrent key press
                        if (fs != null)
                        {
                            // Use SVSFDefault to make sure speech play the wav file
                            fs.Open("correct.wav", SpeechStreamFileMode.SSFMOpenForRead, false);
                            speech.SpeakStream(fs, SpeechVoiceSpeakFlags.SVSFDefault);
                        }

                        // Based on current screen, determine the next screen
                        DetermineNextState();
                    }
                    // Wrong!
                    else
                    {
                        // Play a sound to indicate wrong key press
                        if (fs != null)
                        {
                            // Use SVSFDefault to make sure speech play the wav file
                            fs.Open("wrong.wav", SpeechStreamFileMode.SSFMOpenForRead, false);
                            speech.SpeakStream(fs, SpeechVoiceSpeakFlags.SVSFDefault);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Exception!\n" + ex.Message);
                }
                finally
                {
                    // Make sure file stream close
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }

                PlayCurrentState();
            }
        }
        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;
            }
        }
Example #46
0
        private void btnPlayVox_Click(object sender, System.EventArgs e)
        {
            try
            {

                if (chkSaveToWavFile.Checked)
                {
                    Voice.Speak(txtSpeakText.Text, SpFlags);

                    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
                {
                    try
                    {
                        Voice.Speak(txtSpeakText.Text, SpFlags);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(this, ex.Message.ToString() + "::" + ex.StackTrace.ToString());
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString() + "::" + ex.StackTrace.ToString());
            }
        }