Pronounce Highlighted Word

Text to Speech: For C# and VB NET Students

 

You might not want all the text in your text box to be read out. You might, for example, be unsure of the pronunciation of just one or two words or phrases. In which case, it would be a nice feature if you could highlight a word (or words) you're unsure about and have it (them) read out.

Double-click your Pronounce button. Now add this code to it in C#: (You've done most of it before so you can just copy and paste from elsewhere in your code.)

string voice = cmbVoice.Text;

if (voice == "Select Voice")
{

MessageBox.Show("Select a Voice");
return;

}

if (txtSpeechText.Text.Trim() == "")
{

MessageBox.Show("Type some text");
return;

}

if (txtSpeechText.SelectionLength > 0)
{

string sel = txtSpeechText.SelectedText;
SpeechSynthesizer syn = new SpeechSynthesizer();
syn.SetOutputToDefaultAudioDevice();
syn.SelectVoice(voice);
syn.Speak(sel.Trim());
syn.Dispose();

}

Here's your lines, VB Net coders:

Dim voice As String = cmbVoice.Text

If voice = "Select Voice" Then

MessageBox.Show("Select a Voice")
Exit Sub

End If

If txtSpeechText.Text.Trim() = "" Then

MessageBox.Show("Type some text")
Exit Sub

End If

If txtSpeechText.SelectionLength > 0 Then

Dim sel As String = txtSpeechText.SelectedText
Dim syn As SpeechSynthesizer = New SpeechSynthesizer()
syn.SetOutputToDefaultAudioDevice()
syn.SelectVoice(voice)
syn.Speak(sel.Trim())
syn.Dispose()

End If

The only two lines you haven't met are these two:

txtSpeechText.SelectionLength
string sel = txtSpeechText.SelectedText;

The first one is in the final if statement and just checks if the SelectionLength is greater than zero. The second line gets the SelectedText. Note that we're also using Speak rather than the SpeakAsync we used before. For single words or short phrases, Speak is fine.

Try it out. Load a file in your text box. Highlight a word or words. Select a voice and click your Speak button. The highlighted word or words will be read out to you.

 

In the last lesson of this walkthrough, we'll examine one more feautre that might be useful: grabbing text from a website and reading that out.

Get Web URL Text >>

Back to the C# NET Contents Page

Back to the VB NET Contents Page