Home and Learn: Intermediate Programming
Text to Speech: For C# and VB NET Students
From the previous lesson, we have a routine that detects which file type you are trying to open. But we need to write the Subs/methods to do the actual opening of the files. We'll open text files in this lesson.
Add this method to your code in C#:
private void GetTextFile(string filePath)
{
}
And this Sub in VB Net:
Private Sub GetTextFile(filePath As String)
End Sub
We'll use a StreamReader to open the text file. This is in the System.IO namespace.
In your GetTextFile method in C#, set up a new StreamReader with this line:
StreamReader objReader = new StreamReader(filePath);
In VB Net, your line is this:
Dim objReader As StreamReader = New StreamReader(filePath)
Whatever text file we hand over to our GetTextFile Sub/method will be in the filePath variable. This is the file that is in the round brackets of StreamReader.
You can read this straight into the text box. Add this line (without the semicolon in VB):
txtSpeechText.Text = objReader.ReadToEnd();
Finally, we can close the reader with this (again, without the semicolon in VB):
objReader.Close()
Now we only need to call it into action.
Go back to your Open File button code. In place of the MessageBox.Show("Text File") line in the if statement for text files, add this (delete the semicolon on the end in VB):
GetTextFile(fileName);
Here's what your Open File button and GetTextFile method should look like in C#:
Your Open File button and GetTextFile Sub should look like this in VB Net:
You can try it out now. Run your program and click your Open File button. Select a text file on your computer and click Open. It should appear in the text box. Select a Voice from the dropdown box and then click your Speak button. You should hear the text file being read out. Here's a 1-minute video of our program in action (there's no sound until Microsoft David starts to read out the text).
In the next lesson below, we'll open a PDF and grab the text.
Back to the Intermediate Programming Contents Page
Email us: enquiry at homeandlearn.co.uk