Chuyển giọng nói sang text C#




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.Speech;
using System.Speech.Recognition;
using System.Threading;

namespace Speech_To_Text
{
    public partial class Form1 : Form
    {
        public SpeechRecognitionEngine recognizer;
        public Grammar grammar;
        public Thread RecThead;
        public Boolean RecognizerState = true;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //thiết lập Grammar
            GrammarBuilder builde = new GrammarBuilder();
            builde.AppendDictation();
            grammar = new Grammar(builde);

            recognizer = new SpeechRecognitionEngine();
            recognizer.LoadGrammar(grammar);
            recognizer.SetInputToDefaultAudioDevice();
            recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
         
            RecognizerState = true;
            RecThead = new Thread(new ThreadStart(RecTheadFuntion));
            RecThead.Start();
        }

        public void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            //nhận diện âm thanh
            if (!RecognizerState)
                return;
            this.Invoke((MethodInvoker)delegate
            {
                textBox1.Text += (" " + e.Result.Text.ToLower());
            });
        }

        public void RecTheadFuntion()
        {
            //thực hiện nhận diện giọng nói
            while (true)
            {
                try
                {
                    recognizer.Recognize();
                }
                catch
                {

                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            RecThead.Abort();
            RecThead = null;
            recognizer.UnloadAllGrammars();
            recognizer.Dispose();
            grammar = null;
        }

        private void btnEnableSpeech_Click(object sender, EventArgs e)
        {
            RecognizerState = true;
        }

        private void btnDisableSpeech_Click(object sender, EventArgs e)
        {
            RecognizerState = false;
        }

     

    }
}


Share this

Previous
Next Post »