コード例 #1
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());
     }
 }
コード例 #2
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
        }
コード例 #3
0
        private void TtsSave()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Title            = "保存声音";
            saveFileDialog.Filter           = "*.wav|*.wav|*.mp3|*.mp3";
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            DialogResult saveDialog = saveFileDialog.ShowDialog();

            try
            {
                if (saveDialog == System.Windows.Forms.DialogResult.OK)
                {
                    SpeechLib.SpeechStreamFileMode SSFM = SpeechLib.SpeechStreamFileMode.SSFMCreateForWrite;
                    SpeechLib.SpFileStream         sfs  = new SpeechLib.SpFileStream();
                    sfs.Open(saveFileDialog.FileName, SSFM, false);
                    voice.AudioOutputStream = sfs;
                    Tts();
                    voice.WaitUntilDone(System.Threading.Timeout.Infinite);
                    sfs.Close();
                    System.Diagnostics.Process.Start("Explorer.exe", string.Format(@"/select,{0}", saveFileDialog.FileName));//打开wav目录并选中文件
                }
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #4
0
ファイル: SpeechTask.cs プロジェクト: Kristd/backup
        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
            {

            }
        }
コード例 #5
0
		/// <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();
			}
		}
コード例 #6
0
        protected void clickToSpeech_Click(object sender, EventArgs e)
        {
            SpVoice objspeech = new SpVoice();

            objspeech.Speak(prathyusha.Text.Trim(), SpeechVoiceSpeakFlags.SVSFDefault);
            objspeech.WaitUntilDone(System.Threading.Timeout.Infinite);
        }
コード例 #7
0
 IEnumerator WaitForSpeach()
 {
     while (!voice.WaitUntilDone(1))
     {
         yield return(null);
     }
     transform.SendMessage("DoneSpeaking");
 }
コード例 #8
0
ファイル: SpeechCall.cs プロジェクト: Wooyme/HIS-1
        /// <summary>
        /// ÓïÒô
        /// </summary>
        /// <param name="callString"></param>
        public void SpeechCalling(string callString)
        {
            speech.WaitUntilDone(-1);
            //ÖÕÖ¹ÏÈÇ°ÀʶÁ,Èç¹ûÓÐ
            //speech.Speak(" ", SpeechVoiceSpeakFlags.SVSFlagsAsync);

            //speech.Word += new _ISpeechVoiceEvents_WordEventHandler(speech_Word);

            speech.Speak(callString, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }
コード例 #9
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();
    }
コード例 #10
0
 public void TTSToFile(string text, string filepath)
 {
     if (!File.Exists(filepath))
     {
         File.Create(filepath);
     }
     spFileStream.Open(filepath, spFileMode);
     my_Voice.AudioOutputStream = spFileStream;
     my_Voice.Speak(text, my_Spflag);
     my_Voice.WaitUntilDone(-1);
     spFileStream.Close();
 }
コード例 #11
0
ファイル: Form1.cs プロジェクト: yzh867609570/test
 //文字转语音录频
 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("转换音频文件成功");
 }
コード例 #12
0
ファイル: ChamadaFunc.cs プロジェクト: gege69/Players
 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);
 }
コード例 #13
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();
            }
        }
コード例 #14
0
        /// <summary>
        /// 语音播放
        /// </summary>
        public static void NewRead()
        {
            try
            {
                //读取已有文件
                string            wavPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Sounds\\ring.wav";//要读的音频文件地址
                SpVoiceClass      pp      = new SpVoiceClass();
                SpFileStreamClass spFs    = new SpFileStreamClass();
                spFs.Open(wavPath, SpeechStreamFileMode.SSFMOpenForRead, true);
                ISpeechBaseStream Istream = spFs as ISpeechBaseStream;

                //文字转语音播放
                SpeechVoiceSpeakFlags spFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
                SpVoice spVoice = new SpVoice();                                                                                  //声源
                spVoice.Rate   = Convert.ToInt32(System.Configuration.ConfigurationManager.ConnectionStrings["Rate"].ToString()); //速度
                spVoice.Volume = 100;
                spVoice.WaitUntilDone(-1);
                spVoice.SpeakStream(Istream, spFlags);
                //循环播放
                for (int i = 0; i < readCount; i++)
                {
                    spVoice.WaitUntilDone(-1);
                    spVoice.Speak(readTxt, spFlags);//文字转语音播放
                }
                spFs.Close();
                //直接读取音频文件
                //SoundPlayer soundPlayer = new SoundPlayer();
                //soundPlayer.SoundLocation = wavPath;
                //soundPlayer.Load();
                //soundPlayer.Play();
            }
            catch (Exception err)
            {
                MessageBox.Show("语音播报失败!");
                CommonalityEntity.WriteTextLog(err.ToString());
            }
        }
コード例 #15
0
ファイル: Syntx.cs プロジェクト: aco228/RikiMusician
        public static byte[] GetSound(string text)
        {
            const SpeechVoiceSpeakFlags speechFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            var synth  = new SpVoice();
            var wave   = new SpMemoryStream();
            var voices = synth.GetVoices();

            try
            {
                // synth setup
                synth.Volume = 100;
                synth.Rate   = -3;
                foreach (SpObjectToken voice in voices)
                {
                    if (voice.GetAttribute("Name") == "Microsoft Matej")
                    {
                        synth.Voice = voice;
                        break;
                    }
                }

                wave.Format.Type        = SpeechAudioFormatType.SAFT22kHz16BitMono;
                synth.AudioOutputStream = wave;
                synth.Speak(text, speechFlags);
                synth.WaitUntilDone(Timeout.Infinite);

                var waveFormat = new WaveFormat(22050, 16, 1);
                using (var ms = new MemoryStream((byte[])wave.GetData()))
                    using (var reader = new RawSourceWaveStream(ms, waveFormat))
                        using (var outStream = new MemoryStream())
                            using (var writer = new WaveFileWriter(outStream, waveFormat))
                            {
                                reader.CopyTo(writer);
                                //return o.Mp3 ? ConvertToMp3(outStream) : outStream.GetBuffer();

                                //var bytes = ConvertToMp3(outStream);
                                File.WriteAllBytes("speak.wav", outStream.GetBuffer());

                                return(null);
                            }
            }
            finally
            {
                Marshal.ReleaseComObject(voices);
                Marshal.ReleaseComObject(wave);
                Marshal.ReleaseComObject(synth);
            }
        }
コード例 #16
0
ファイル: Speak.cs プロジェクト: tylerbutler/bitworthy
        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);
        }
コード例 #17
0
ファイル: SpeekHelper.cs プロジェクト: shoy160/tjzx
 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;
 }
コード例 #18
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();
        }
コード例 #19
0
ファイル: Mouth.cs プロジェクト: asbelov/Qlasha
        public void Speak()
        {
            System.Threading.Thread.Sleep(50);
            if (!SpeakerSAPI5.WaitUntilDone(0))
            {
                return;
            }

            String Message = MyMemory.Remember();

            if (Message == Properties.Resources.StrEmpty)
            {
                return;
            }

            SpeakerSAPI5.Speak(Message, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }
コード例 #20
0
    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);
    }
コード例 #21
0
    private IEnumerator Speak(string input)
    {
        fileID++;
        string dataPath = Application.dataPath + fileID + fileSuffix;

        spFileStream.Open(dataPath, spFileMode, false);
        spVoice.AudioOutputStream = spFileStream;
        spVoice.Speak(input, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        spVoice.WaitUntilDone(-1);
        spFileStream.Close();

        byte[] data = File.ReadAllBytes(dataPath);

        base.OnTTSResult(new TextToSpeechResultEventArgs(ToAudioClip(data)));
        File.Delete(dataPath);

        yield return(null);
    }
コード例 #22
0
ファイル: SpeekHelper.cs プロジェクト: zs200344/Shoy.Common
        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);
        }
コード例 #23
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);
        }
コード例 #24
0
        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();
            }
        }
コード例 #25
0
ファイル: SpVoiceHelper.cs プロジェクト: zhongshuiyuan/MT2017
        /// <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();
        }
コード例 #26
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);
        }
コード例 #27
0
        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;
            }
        }
コード例 #28
0
        private void btnToWave_Click(object sender, EventArgs e)
        {
            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);
                sp.AudioOutputStream = spFileStream;
                sp.Volume            = trackBar1.Value;
                sp.Rate = trackBar2.Value;
                sp.Speak(tbTextInput.Text, spFlags);
                sp.WaitUntilDone(System.Threading.Timeout.Infinite);
                spFileStream.Close();
            }
        }
コード例 #29
0
        private void SpeakToOutputDevice(string message, string language)
        {
            const SpeechVoiceSpeakFlags speechFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            SpVoice             synth  = new SpVoice();
            SpMemoryStream      wave   = new SpMemoryStream();
            ISpeechObjectTokens voices = synth.GetVoices();

            try
            {
                synth.Rate   = 0;
                synth.Volume = 100;

                wave.Format.Type        = SpeechAudioFormatType.SAFT44kHz16BitStereo;
                synth.AudioOutputStream = wave;

                if (language != null)
                {
                    foreach (SpObjectToken voice in voices)
                    {
                        if (voice.GetAttribute("Name") == language)
                        {
                            synth.Voice = voice;
                        }
                    }
                }

                synth.Speak(message, speechFlags);
                synth.WaitUntilDone(Timeout.Infinite);

                OutputWaveStream(wave);
            }
            finally
            {
                Marshal.ReleaseComObject(voices);
                Marshal.ReleaseComObject(wave);
                Marshal.ReleaseComObject(synth);
            }
        }
コード例 #30
0
        private float[] Synthesize(string text, string outputPath, string language, string voice)
        {
            // Despite the fact that SpVoice.AudioOutputStream accepts values of type ISpeechBaseStream,
            // the single type of a stream that is actually working is a SpFileStream.
            SpFileStream stream      = PrepareFileStreamToWrite(outputPath);
            SpVoice      synthesizer = new SpVoice {
                AudioOutputStream = stream
            };

            string ssmlText = string.Format(ssmlTemplate, language, voice, text);

            synthesizer.Speak(ssmlText, SpeechVoiceSpeakFlags.SVSFIsXML);
            synthesizer.WaitUntilDone(-1);
            stream.Close();

            byte[]  data       = File.ReadAllBytes(outputPath);
            float[] sampleData = TextToSpeechUtils.ShortsInByteArrayToFloats(data);
            float[] cleanData  = RemoveArtifacts(sampleData);

            ClearCache(outputPath);

            return(cleanData);
        }
コード例 #31
0
        public static void NewRead(string content)
        {
            string       wavPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "ring.wav";//要读的音频文件地址
            SpVoiceClass pp      = new SpeechLib.SpVoiceClass();

            SpeechLib.SpFileStreamClass spFs = new SpFileStreamClass();
            spFs.Open(wavPath, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
            SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
            //SoundPlayer soundPlayer = new SoundPlayer();
            //soundPlayer.SoundLocation = wavPath;
            //soundPlayer.Load();
            //soundPlayer.Play();
            SpeechVoiceSpeakFlags spFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            SpVoice spVoice = new SpVoice(); //声源

            spVoice.Rate   = -5;             //速度
            spVoice.Volume = 100;
            //播放
            spVoice.SpeakStream(Istream, spFlags);
            spVoice.WaitUntilDone(-1);
            spVoice.Speak(content, spFlags);
            spFs.Close();
            //生成文件
            //try
            //{
            //    SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
            //    SpFileStream SpFileStream = new SpFileStream();
            //    SpFileStream.Open(@"C:\Users\EMEWE\Desktop\Test.wav", SpFileMode, false);
            //    spVoice.AudioOutputStream = SpFileStream;//设定voice的输出为Stream
            //    spVoice.Speak(txtContent.Text.Trim(), spFlags);
            //    spVoice.WaitUntilDone(Timeout.Infinite);//Using System.Threading;
            //    SpFileStream.Close();
            //    MessageBox.Show("生成成功!");
            //}
            //catch { MessageBox.Show("生成失败!"); }
        }
コード例 #32
0
        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);
        }
コード例 #33
0
ファイル: OrderList.cs プロジェクト: wckj/wc001
 //语音提示公共方法
 public void Voice(string voice)
 {
     SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
     SpVoice Voice = new SpVoice();
     Voice.Rate = -2;
     Voice.Speak(voice, SpFlags);
     Voice.WaitUntilDone(5000);
 }
コード例 #34
0
        /// <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
        }
コード例 #35
0
        static void Main(string[] args)
        {
            string conf_file = AppDomain.CurrentDomain.BaseDirectory + "config.ini";
            Config cfg       = new Config();

            cfg.LoadIniFile(conf_file);
            cfg.SaveIniFile();


            //SpeechVoiceSpeakFlags spFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            SpVoice voice = new SpVoice();

            voice.Rate   = cfg.应用参数.语速; //语速,[-10,10]
            voice.Volume = cfg.应用参数.音量; //音量,[0,100]

            string tts = cfg.应用参数.TTS库; // "Microsoft Lili";//

            // string tts = "MS-Lili-2052-20-DSK";//

            voice.Voice = voice.GetVoices("name=" + tts /*Microsoft Simplified Chinese"*/).Item(0);

            //dynamic vs = voice.GetVoices();
            //System.Console.WriteLine("TTS list:");
            //for (int i = 0; i < vs.Count; i++)
            //{
            //    string s = vs[i].id;
            //    System.Console.WriteLine("" + (i + 1) + ":" + s);
            //}
            //next:
            //System.Console.WriteLine("Please Select:");
            //string ins = System.Console.ReadLine();
            //int sel = int.Parse(ins);
            //if (sel < 0 || sel > vs.Count)
            //    goto next;

            //voice.Voice = voice.GetVoices("name=XiaoKun").Item(0);

            /*
             * dynamic ttss = spVoice.GetVoices();//‘获得语音引擎集合
             * ttss.count
             * ttss.id
             */

            string st = cfg.应用参数.文本;
            string sp = cfg.应用参数.分隔字符串;

            string[] ss = st.Split(new string[] { sp }, StringSplitOptions.None);
            foreach (string s in ss)
            {
                string outname;
                string text;
                if (s.Contains('%'))
                {
                    string[] sst = s.Split('%');
                    outname = sst[0];
                    text    = sst[1];
                }
                else
                {
                    outname = s;
                    text    = s;
                }
                //SpFileStream spfs = new SpFileStream();
                string path = AppDomain.CurrentDomain.BaseDirectory + outname + ".wav";
                System.Console.WriteLine("Output: " + path);
                //spfs.Open(path, SpeechStreamFileMode.SSFMCreateForWrite, false);
                // spfs.Write(voice.)

                Type    type2         = Type.GetTypeFromProgID("SAPI.SpFileStream");
                dynamic objFileStream = Activator.CreateInstance(type2);

                objFileStream.Format.Type = SpeechAudioFormatType.SAFT22kHz16BitMono;
                objFileStream.Open(path, SpeechStreamFileMode.SSFMCreateForWrite, false);
                voice.AudioOutputStream = objFileStream;
                voice.Speak(text, SpeechVoiceSpeakFlags.SVSFlagsAsync);
                voice.WaitUntilDone(-1);
                objFileStream.Close();
                //voice.Speak("老人卡,学生卡,当");// How do you do");
            }
            System.Console.WriteLine("All Convert Ok, Press Any key to exit.");
            System.Console.ReadKey();
        }
コード例 #36
0
 private static void MyCallbackFunction(object s1)
 {
     SpVoice objSpeech = new SpVoice();
     objSpeech.Speak(s1.ToString(),SpeechVoiceSpeakFlags.SVSFlagsAsync);
     objSpeech.WaitUntilDone(-1);
 }
コード例 #37
0
 protected void clickToSpeech_Click(object sender, EventArgs e)
 {
     SpVoice objspeech = new SpVoice();
     objspeech.Speak(prathyusha.Text.Trim(), SpeechVoiceSpeakFlags.SVSFDefault);
     objspeech.WaitUntilDone(System.Threading.Timeout.Infinite);
 }
コード例 #38
0
        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;
            }
        }
コード例 #39
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;
        }
コード例 #40
0
ファイル: MainForm.cs プロジェクト: CavanOrBxj/MSTTS
        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");
            }
        }