img
Home / C# Codes / WINDOWS FORMS: TEXT TO SPEECH IN C#

WINDOWS FORMS: TEXT TO SPEECH IN C#

53 Views

This demo explains how to convert text to speech using C# in Visual Studio 2017 using System.Speech Library

Microsoft .NET framework provides System.Speech.Synthesis for voice synthesis
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project “TextToSpeech” and then click OK
 

Step 2: Design your form as below
 

 
Step 3: Add code to handle your form as below
 
using System;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.IO;
namespace TextToSpeech
{
public partial class frmMain : Form
{
SpeechSynthesizer voice;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
voice = new SpeechSynthesizer();
}
private void btnSpeak_Click(object sender, EventArgs e)
{
try
{
//Select voice
switch (cboSelectVoice.SelectedIndex)
{
case 0:
voice.SelectVoiceByHints(VoiceGender.NotSet);
break;
case 1:
voice.SelectVoiceByHints(VoiceGender.Male);
break;
case 2:
voice.SelectVoiceByHints(VoiceGender.Female);
break;
case 3:
voice.SelectVoiceByHints(VoiceGender.Neutral);
break;
default:
break;
}
voice.SpeakAsync(txtContent.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Message”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnPause_Click(object sender, EventArgs e)
{
try
{
voice.Pause();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Message”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnResume_Click(object sender, EventArgs e)
{
try
{
voice.Resume();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Message”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
//Save text to wav file
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = “Wav files|*.wav”;
sfd.Title = “Save to a wave file”;
if (sfd.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
voice.SetOutputToWaveStream(fs);
voice.Speak(txtContent.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, “Message”, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
 
 

  • Facebook
  • Twitter
  • Linkedin
  • Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar