Csharp: speech to text, text to speech in win

Source: Internet
Author: User
Tags sapi

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 references that the Microsoft Speech object library Reference of the Speech sdk 5.1 in the COM tab already has Version 11.0 using System. speech; using System. speech. recognition; using System. speech. synthesis; namespace Speech {// <summary> // 20140427 // tu juwen ///// </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; // obtain the total number of voice libraries // bool result = false; // for (int I = 0; I <count; I ++) // {// string desc = obj. item (I ). getDescription (I );//. getDescription (); // traverse the voice library // comboBox1.Items. add (desc); // SpVoiceClass voice = new SpVoiceClass (); // SAPI 5.1 // voice. voice = voice. getVoices (string. empty, string. empty ). item (0); // voice. speak ("what you want to say", SpeechVoiceSpeakFlags. SVSFlagsAsync); // SpVoice voice1 = new SpVoice (); // SAPI 5.4 // voice1.Volume = 100; // volume // voice1.Voice = voice1.GetVoices (string. empty, string. empty ). item (0); // voice1.Rate = 2; // Speed Speech reading speed // voice1.Speak ("what you want to say", SpeechVoiceSpeakFlags. SVSFlagsAsync); // voice1.Speak ("speech sdk 5.1", SpeechVoiceSpeakFlags. SVSFlagsAsync); // SpeechSynthesizer syn = new SpeechSynthesizer (); // syn. selectVoice ("Microsoft Lili"); // initialize recognizer and synthesizer evaluate (); // if input device found then proceed if (SelectInputDevice () {LoadDictationGrammar (); readAloud ("People's Republic of China "); // Speech Engine Ready for Input in Chinese format }/// <summary> /// Chinese // </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> private void button#click (object sender, eventArgs e) {SpVoiceClass voice = new SpVoiceClass (); voice. voice = voice. getVoices (string. empty, string. empty ). item (0); // 0, which is the default value of voice. speak (this. textBox1.Text. trim (), SpeechVoiceSpeakFlags. SVSFlagsAsync );} /// <summary> // english // </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> /// input Chinese speech and output Chinese Text /// </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 <identifier> (identifier); synthesizer = new SpeechSynthesizer () ;}# region Recognizer events private void identifier (object sender, identifier 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 abve XP if (IsOscompatible () {try {recognizer. setinputtodefaauaudiodevice ();} 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. setinputtodefaauaudiodevice ();} // <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 );}}}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.