Csharp: speech to text, text to speech in win

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using SpeechLib;//NET2.0 引用 Speech sdk 5.1 在COM选项卡里面的Microsoft Speech  object  library引用 已经有11.0版本
using System.Speech;
using System.Speech.Recognition;
using System.Speech.Synthesis;

namespace Speech
{
    /// <summary>
    /// 20140427
    /// 涂聚文
    ///
    /// </summary>
    public partial class Form1 : Form
    {
        private enum State
        {
            Idle = 0,
            Accepting = 1,
            Off = 2,
        }

        private State RecogState = State.Off;
        private SpeechRecognitionEngine recognizer;
        private SpeechSynthesizer synthesizer = null;
        private int Hypothesized = 0;
        private int Recognized = 0;
        /// <summary>
        ///
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            // SpVoice voice = new SpVoice();//SAPI 5.4
            //SpeechLib.ISpeechObjectTokens obj = voice.GetVoices(string.Empty, string.Empty);
            //int count = obj.Count;//获取语音库总数
            //bool result = false;
            //for (int i = 0; i < count; i++)
            //{
            //    string desc = obj.Item(i).GetDescription(i);//.GetDescription(); //遍历语音库

            //    comboBox1.Items.Add(desc);
            //}

            //SpVoiceClass voice = new SpVoiceClass();//SAPI 5.1
            ////voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0);
            ////voice.Speak("你要说的话",SpeechVoiceSpeakFlags.SVSFlagsAsync);

            //SpVoice voice1 = new SpVoice();//SAPI 5.4
            //voice1.Volume = 100;//音量
            //voice1.Voice = voice1.GetVoices(string.Empty, string.Empty).Item(0);

            //voice1.Rate = 2;//速度语音朗读速度
            //           voice1.Speak("你要说的话", SpeechVoiceSpeakFlags.SVSFlagsAsync);
             //voice1.Speak("speech sdk 5.1", SpeechVoiceSpeakFlags.SVSFlagsAsync);
            //SpeechSynthesizer syn = new SpeechSynthesizer();
            //syn.SelectVoice("Microsoft Lili"); 

            //initialize recognizer and synthesizer
            InitializeRecognizerSynthesizer();

            //if input device found then proceed
            if (SelectInputDevice())
            {
                LoadDictationGrammar();

                ReadAloud("中华人民共和国"); //中文方式Speech Engine Ready for Input
            }

        }
        /// <summary>
        /// 中文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            SpVoiceClass voice = new SpVoiceClass();
            voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(0); //0,为系统默认,中文

            voice.Speak(this.textBox1.Text.Trim(), SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }
        /// <summary>
        /// 英文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            SpVoiceClass voice = new SpVoiceClass();
            voice.Voice = voice.GetVoices(string.Empty, string.Empty).Item(1);//
            voice.Speak(this.textBox2.Text.Trim(), SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }
        /// <summary>
        /// 输入中文语音输出中文文字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            switch (RecogState)
            {
                case State.Off:
                    RecogState = State.Accepting;
                    button3.Text = "Stop";
                    recognizer.RecognizeAsync(RecognizeMode.Multiple);
                    break;
                case State.Accepting:
                    RecogState = State.Off;
                    button3.Text = "Start";
                    recognizer.RecognizeAsyncStop();
                    break;
            }
        }
        /// <summary>
        /// pause recognition and speak the text sent
        /// </summary>
        /// <param name="speakText"></param>
        public void ReadAloud(string speakText)
        {
            try
            {
                recognizer.RecognizeAsyncCancel();
                synthesizer.SpeakAsync(speakText);
            }
            catch { }
        }

        /// <summary>
        /// initialize recognizer and synthesizer along with their events
        /// /// </summary>
        private void InitializeRecognizerSynthesizer()
        {
            var selectedRecognizer = (from e in SpeechRecognitionEngine.InstalledRecognizers()
                                      where e.Culture.Equals(Thread.CurrentThread.CurrentCulture)
                                      select e).FirstOrDefault();
            recognizer = new SpeechRecognitionEngine(selectedRecognizer);
            recognizer.AudioStateChanged += new EventHandler<AudioStateChangedEventArgs>(recognizer_AudioStateChanged);
            recognizer.SpeechHypothesized += new EventHandler<SpeechHypothesizedEventArgs>(recognizer_SpeechHypothesized);
            recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);

            synthesizer = new SpeechSynthesizer();
        }
        #region Recognizer events
        private void recognizer_AudioStateChanged(object sender, AudioStateChangedEventArgs e)
        {
            switch (e.AudioState)
            {
                case AudioState.Speech:
                    LabelStatus.Text = "Listening";
                    break;
                case AudioState.Silence:
                    LabelStatus.Text = "Idle";
                    break;
                case AudioState.Stopped:
                    LabelStatus.Text = "Stopped";
                    break;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void recognizer_SpeechHypothesized(object sender, SpeechHypothesizedEventArgs e)
        {
            Hypothesized++;
            LabelHypothesized.Text = "Hypothesized: " + Hypothesized.ToString();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            Recognized++;
            string s = "Recognized: " + Recognized.ToString();

            if (RecogState == State.Off)
                return;
            float accuracy = (float)e.Result.Confidence;
            string phrase = e.Result.Text;
            {
                if (phrase == "End Dictate")
                {
                    RecogState = State.Off;
                    recognizer.RecognizeAsyncStop();
                    ReadAloud("Dictation Ended");
                    return;
                }
                textBox1.AppendText(" " + e.Result.Text);
            }
        }
        #endregion
        /// <summary>
        /// select input device if available
        /// </summary>
        /// <returns></returns>
        private bool SelectInputDevice()
        {
            bool proceedLoading = true;
            //if OS is above XP
            if (IsOscompatible())
            {
                try
                {
                    recognizer.SetInputToDefaultAudioDevice();
                }
                catch
                {
                    proceedLoading = false; //no audio input device
                }
            }
            //if OS is XP or below
            else
                ThreadPool.QueueUserWorkItem(InitSpeechRecogniser);
            return proceedLoading;
        }

        /// <summary>
        /// Findout if OS is compatible.
        /// </summary>
        /// <returns>true if greater than XP otherwise false</returns>
        private bool IsOscompatible()
        {
            OperatingSystem osInfo = Environment.OSVersion;
            if (osInfo.Version > new Version("6.0"))
                return true;
            else
                return false;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="o"></param>
        private void InitSpeechRecogniser(object o)
        {
            recognizer.SetInputToDefaultAudioDevice();
        }

        /// <summary>
        /// Load grammars, one for command and other for dictation
        /// </summary>
        private void LoadDictationGrammar()
        {
            GrammarBuilder grammarBuilder = new GrammarBuilder();
            grammarBuilder.Append(new Choices("End Dictate"));
            Grammar commandGrammar = new Grammar(grammarBuilder);
            commandGrammar.Name = "main command grammar";
            recognizer.LoadGrammar(commandGrammar);

            DictationGrammar dictationGrammar = new DictationGrammar();
            dictationGrammar.Name = "dictation";
            recognizer.LoadGrammar(dictationGrammar);
        }
    }
}
时间: 2025-01-26 13:02:20

Csharp: speech to text, text to speech in win的相关文章

csharp:Google TTS API text to speech

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Threading; using N

speech sdk训练-用微软SPEECH SDK开发时,怎么添加训练文件

问题描述 用微软SPEECH SDK开发时,怎么添加训练文件 微软SPEECH SDK只提供了默认的训练文件,但是我在网上看见了可以添加自己的配置文件,请问怎么设置?

重新想象 Windows 8.1 Store Apps (87) - TTS: Speak Text, Speak SSML

原文:重新想象 Windows 8.1 Store Apps (87) - TTS: Speak Text, Speak SSML [源码下载] 重新想象 Windows 8.1 Store Apps (87) - TTS: Speak Text, Speak SSML 作者:webabcd 介绍重新想象 Windows 8.1 Store Apps 之 TTS(Text To Speech) Speak Text Speak SSML 示例1.演示如何通过 TTS 朗读一段文本,以及如何将其保

(zhuan) Speech and Natural Language Processing

  Speech and Natural Language Processing obtain from this link: https://github.com/edobashira/speech-language-processing A curated list of speech and natural language processing resources. Other lists can be found in this list. If you want to contrib

TX Text Control文字处理教程(8)使用超链接

本章节将演示如何在文档中添加超链接和锚点,以及如何响应超链接的单击操作. 本章节相应的源代码可以在TX Text Control.NET的安装目录中找到:         Samples\WinForms\VB.NET\ Hyperlinks         Samples\WinForms\CSharp\ Hyperlinks 第一步:插入超链接         在这个示例程序中将在文档里插入一个超链接,并将该文档保存为HTML格式,便于在浏览器中显示.         为了在文档中插入超

TX Text Control文字处理教程(11)使用文本框

本章主要讲述如何利用文本框控件来控制和操作文本.相应的源代码可以在TX Text Control.NET的安装目录中找到:         Samples\WinForms\VB.NET\ Text Frames         Samples\WinForms\CSharp\ Text Frames 第一步:插入文本框 插入文本框操作首先需要创建一个 TextFrame 的实例, 然后将其添加到 TextFrameCollection集合对象中. [C#] TXTextControl.Te

MySQL和MSSQL下,text 、ntext、 image、blob的比较

MySQL和MSSQL下,text .ntext. image.blob的比较2009-12-30 13:371.MySQL存在text和blob:  (1)相同  在TEXT或BLOB列的存储或检索过程中,不存在大小写转换,当未运行在严格模式时,如果你为BLOB或TEXT列分配一个超过该列类型的最大长度的值值,值被截取以保证适合.如果截掉的字符不是空格,将会产生一条警告.使用严格SQL模式,会产生错误,并且值将被拒绝而不是截取并给出警告. BLOB和TEXT列不能有 默认值. 当保存或检索BL

文字布局(TEXT STYLE)标记(TAGS)

行的控制 段(Paragraph) (可以看作是空行) <p> 你好吗?<p>很好. 你好吗? 很好. 换行 <br> 你好吗?<br>很好. 你好吗?很好. 不换行<nobr> <nobr> 请改变您浏览器窗口的宽度, 使之小于这一行的宽度, 看看这个标记的作用!</nobr> 请改变您浏览器窗口的宽度,使之小于这一行的宽度,看看这个标记的作用! 文字的对齐(Alignment) <hn align=#>..

HTML文字布局(TEXT STYLE)标记(TAGS)

行的控制 <------Paragraph-------> 段(Paragraph) (可以看作是空行) <p> 你好吗?<p>很好. 你好吗? 很好. <------Break Line-------> 换行 <br> 你好吗?<br>很好. 你好吗?很好. <------No Break-------> 不换行<nobr> <nobr> 请改变您浏览器窗口的宽度, 使之小于这一行的宽度, 看看这