Click here to Skip to main content
Click here to Skip to main content

Text to Speech

By , 17 Apr 2011
 

Introduction

Text To Speech becomes very easy in C#. We know speech technology is very useful for the blind. Now, we are going to learn how to implement speech technology in our project.

text to speak

STEPS

  1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.
  2. On the Microsoft Visual Studio Start Page, click the New Project icon.
  3. On the Microsoft Visual Studio Start Page, click the New Project icon.
  4. In C# projects Templates list, select Windows | WindowsApplication.
  5. In the Name field, enter the name “text to speak”
  6. In the upper right hand corner, ensure that version 4.0 of the .NET Framework is selected.
  7. Accept the default location and Solution Name. Click the OK button. The solution will be created.
  8. Right-click on the Text to Speak project node and select Add Reference.
  9. Under the .NET tab in the Add Reference dialog box, select System.Speech.
  10. Click the OK button.

Select a Text File

Select a text file to convert audio.selected text file display on rich text box.

private void Browse_Click(object sender, EventArgs e)
    {
        OpenFileDialog Ofg = new OpenFileDialog();

        try
        {
            Ofg.CheckFileExists = true;
            Ofg.CheckPathExists = true;
            Ofg.DefaultExt = "txt";
            Ofg.DereferenceLinks = true;
            Ofg.Filter = "Text files (*.txt)|*.txt|" +
				"RTF files (*.rtf)|*.rtf|" +
                              " +
				Works 6 and 7 (*.wps)|*.wps|" +
                              "Windows Write (*.wri)|*.wri|" +
				"WordPerfect document (*.wpd)|*.wpd";
            Ofg.Multiselect = false;
            Ofg.RestoreDirectory = true;
            Ofg.ShowHelp = true;
            Ofg.ShowReadOnly = false;
            Ofg.Title = "Select a file ";
            OpenFile.ValidateNames = true;

            if (OpenFile.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(ofg.OpenFile());
                richTextBox1.Text = sr.ReadToEnd();
            }
        }
        catch
        {
            MessageBox.Show("can not open the file", "Text two speech");
        }
    }

Here, first creating object instance for OpenFileDialog.stream reader is used to read a text file.

Text to Speak

SpeakAsync method is used to speak a word. There are two properties used here; one is volume, another one is Rate. voice gender is also one of the properties. It is used to select voice gender (enum NotSet, Male, Female, Neutral). If any error occurred, message box shows error message.

private void speak_Click(object sender, EventArgs e)
{
    SpeechSynthesizer speak = new SpeechSynthesizer();

try
{
    switch (comboBox1.SelectedItem.ToString())
                {
                    case "NotSet":
                        voice.SelectVoiceByHints(VoiceGender.NotSet);
                            break;
                    case "Male":
                        voice.SelectVoiceByHints(VoiceGender.Male);
                             break;
                    case "Female":
                        voice.SelectVoiceByHints(VoiceGender.Female);
                             break;
                    case "Neturl":
                        voice.SelectVoiceByHints(VoiceGender.Neutral);
                             break;
                  }  

The above code can change voice gender. speakAsyn is an asynchronous method. It means return immediately and speak as a background process. If any error occurred, it will display on message box.

voice.Volume = trackBar1.Value;
voice.Rate = trackBar2.Value;
voice.SpeakAsync(richTextBox1.Text);  

Save Audio File

Text converted to audio stream .audio stream can save wav file format. The following steps are used to save wav file.

  1. Create object instance for Save File Dialog.
  2. Set audio stream to select file.
SaveFileDialog sfd = new SaveFileDialog();

sfd.Filter = ""wav files (*.wav)|*.wav";
sfd.Title = "Save to a wave file";
sfd.FilterIndex = 2;
sfd.RestoreDirectory = true;

if (sfd.ShowDialog() == DialogResult.OK)
{
     FileStream fs = new FileStream(sfd.FileName,FileMode.Create,FileAccess.Write);
     voice.SetOutputToWaveStream(fs);
     voice.Speak(richTextBox1.Text);
     fs.Close();
}

Points of Interest

If you want to know more about speech technology, click on this link on the Microsoft website.

History

  • 14th April, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

karthik.B.E
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionkarthik.B.E.memberRahul Kumar Ghosh1 May '13 - 6:37 
I AM HAVING AN APPLICATION FULLY READY IN C#.
NOW I WANT TO MADE IT VOICE RECOGNIZABLE APPLICATION...
AS I AM NEW INTO THIS "SPEECH FILED", I WANT A DEMO EXAMPLE FOR THIS (FULL EXAMPLE WITH COMMENTS) WHICH WOULD INCLUDE TEXTBOX AND BUTTONS.
I WILL SAY "TEXTBOX1" IT WILL FOCUS ON TEXTBOX1 AND THEN I WILL SAY "TEXT FOR TEXTBOX1" IT WILL ENTER THE FULL TEXT INTO THE TEXTBOX1, SAME THING FOR TEXTBOX2 (I WANT 2 TEXTBOX JUST FOR A GOOD UNDERSTANDING, OF HOW TO CHANGE FOCUS BETWEEN CONTROLS),THEN I WILL SAY "1STBUTTON CLICK" AND IT WILL GET CLICKED, <<(NOW A BIG THING)>> ON CLICK OF BUTTON THAT BUTTON IT WILL SHOW MESSAGEBOX, AND I WANT THAT TEXT FROM THE MESSAGE BOX TO BE READ OUT..............
SO ANY HELP WILL BE APPRICIATED
GeneralMy vote of 5memberJitesh R. Neve24 Jan '13 - 1:39 
Really Very Good Article Smile | :)
QuestionMore voicesmemberkiquenet.com22 Jan '13 - 21:14 
It's great.
 
Only voice installed by default, Microsoft Anna (English United States). How can I installed more voice (Spanish) for System.Speech?
kiquenet.com

GeneralMy vote of 5memberKr.Prakash5 Dec '12 - 0:23 
It is very usefull to me
QuestionHow to add TTS engine for windows 7memberKiran Naveen11 Nov '12 - 18:32 
Thanks a lot..
 
I Have download the project, after execution i was not able to change the voice from female to male, If not wrong i feel i have to install the tts engine to make it work. If yes then how to install the tts engine to windows 7 and is Mary and Mike available for windows 7..?
 
Please help it out, thanks in advance.
AnswerCursor animationmemberchprogmer3 Jun '11 - 23:47 
Nice program.
 
Is it easy to add a cursor animation ?
I mean: while speaking, each word is selected, in order to follow (see) the progression.
 
Thanks
GeneralMy vote of 3memberSercanOzdemir17 May '11 - 2:22 
Should be a beginner tag
Generalsome rantingmemberalxxl19 Apr '11 - 1:31 
"Text two speech" - is it joke or bad English? You describe file selection in detail, but from article isn't clear what "voice" variable type is and what references are needed for speech to work. Focus on main things first.
GeneralIf my PC has multipul soundcards, how to specify the output to which soundcard?memberzhangzq7118 Apr '11 - 2:29 
It is a good article, but I want to know how to specify the speech output to which soundcard?
 
Thanks.
email:zhangzq71@hotmail.com

AnswerRe: If my PC has multipul soundcards, how to specify the output to which soundcard?groupkarthik.B.E19 Apr '11 - 4:01 
default sound card will play the sound

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 17 Apr 2011
Article Copyright 2011 by karthik.B.E
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid