This post is about how to implement text to speech on a Windows Form.
Ctrl + Shift + N > Select Visual C# > Select Windows Classic Desktop > Click Windows Forms App (.Net Framework) > click Ok.
- Drag and drop a textbox on the form and set the multiline property as True.
- Drag and drop a button on the form.
Refer to the System.Speech.dll from the following location,
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\YOUR .NET FRAMEWORK VERSION\System.Speech.dll
Example:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Speech.dll
Add the following reference on top,
- using System.Speech.Synthesis;
In the design mode, double click on the button to generate the click event.
Paste the following code in the generated button click event.
-
- if (textBox1.Text.Trim().Length <= 0) {
- MessageBox.Show("Please enter a text for the system to speak.");
- } else {
- string toSpeak = textBox1.Text;
- SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
- speechSynthesizer.Speak(toSpeak);
- speechSynthesizer.Dispose();
- }
-
Run the code by pressing F5. Now, enter some text that you want the system to say.
Thank you