In this article, we will learn how to create a Text to Speech Converter in a C# Windows Forms application using the SpeechSynthesizer class.
Let's Begin
Step 1
Create a new project then select Windows Forms application in C# and give it a name.
Step 2
Drop a RichTextBox and four Button Controls from the ToolBox.
Step 3
Right-click on the References Folder then click on Add Reference.
Step 4
Select the System.Speech Assembly and click on OK.
After adding it, you will see System.Speech assembly under the References folder.
Step 5
Go to Form1.cs (code behind .cs file) and add System.Speech (the System.Speech namespace contains types that support speech recognition) and System.Speech.Synthesis namespace (the System.Speech.Synthesis namespace contains classes for initializing and configuring a speech synthesis engine and for generating speech and so on).
- using System;
- using System.Windows.Forms;
- using System.Speech;
- using System.Speech.Synthesis;
-
- namespace TextToSpeechConverter
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- SpeechSynthesizer speechSynthesizerObj;
- private void Form1_Load(object sender, EventArgs e)
- {
- speechSynthesizerObj = new SpeechSynthesizer();
- btn_Resume.Enabled = false;
- btn_Pause.Enabled = false;
- btn_Stop.Enabled = false;
- }
-
-
- private void btn_Speak_Click(object sender, EventArgs e)
- {
-
- speechSynthesizerObj.Dispose();
- if(richTextBox1.Text!="")
- {
- speechSynthesizerObj = new SpeechSynthesizer();
-
- speechSynthesizerObj.SpeakAsync(richTextBox1.Text);
- btn_Pause.Enabled = true;
- btn_Stop.Enabled = true;
- }
- }
-
- private void btn_Pause_Click(object sender, EventArgs e)
- {
- if(speechSynthesizerObj!=null)
- {
-
- if(speechSynthesizerObj.State==SynthesizerState.Speaking)
- {
-
- speechSynthesizerObj.Pause();
- btn_Resume.Enabled = true;
- btn_Speak.Enabled = false;
- }
- }
- }
-
- private void btn_Resume_Click(object sender, EventArgs e)
- {
- if (speechSynthesizerObj != null)
- {
- if (speechSynthesizerObj.State == SynthesizerState.Paused)
- {
-
- speechSynthesizerObj.Resume();
- btn_Resume.Enabled = false;
- btn_Speak.Enabled = true;
- }
- }
- }
-
- private void btn_Stop_Click(object sender, EventArgs e)
- {
- if(speechSynthesizerObj!=null)
- {
-
- speechSynthesizerObj.Dispose();
- btn_Speak.Enabled = true;
- btn_Resume.Enabled = false;
- btn_Pause.Enabled = false;
- btn_Stop.Enabled = false;
- }
- }
- }
- }
Final PreviewI hope you like this. Thanks.