Creating a Simple Text to Speech App - Page 1
       by kirupa  |  20 August 2007

One of the nice things about the .NET Framework is that the groundwork for what you want to do is already there. For example, in this tutorial, you will learn how to create a simple application that plays aloud a string of text. The process by which text gets converted to sound is fairly complicated, but thankfully, echoing the first sentence, a collection of classes for doing just that are provided for you out of the box. You just have to write a few lines using the existing classes.

This introductory tutorial is designed to help you get more practice with Blend and Visual Studio / C# Express integration. You are not expected to have much prior experience developing WPF applications, but you will be more familiar with the application if you have already completed the Creating a WPF App Using Blend tutorial.

By the end of this tutorial, you will have created an application that looks and behaves (click to run) similarly to the following image:

You can run the application on your computer by checking it out here: http://www.kirupafx.com/ItSpeaks/publish.htm (FFClickOnce if you are running FF).

The above application is quite simple to create, so this should be a fun introductory tutorial that covers how to create a simple user interface and use text-to-speech functionality from an external namespace using Expression Blend and Visual Studio / Visual C# Express.

Let's get started:

  1. Launch Expression Blend and from the Create New Project window, create a new Standard Application (.exe) called ItSpeaks:

[ create a new project called ItSpeaks ]

Press OK to close the window and to create your new project called ItSpeaks.

  1. You will now see an empty window. Select your window, and from the Properties tab, set your window's width and height to 360 by 160 respectively. Your window will now be resized to look like the following image:

[ you will see an empty window in your Artboard ]

  1. Resizing the image is just one of the several changes we are going to make to our window. From the same Properties panel, find the Common Properties panel and give your Window the title Speech Synthesizer.
  2. Staying with the Common Properties panel, find the ResizeMode combobox and change the selected value to NoResize. Your Common Properties panel should look like the following image after making the changes listed in this and the previous step:

[ your Title and ResizeMode have been changed ]

  1. Right now your window is still pretty bland. Let's give it a nice background gradient. With your Window still selected in the Artboard, glance over to the Brushes panel and select the Background property:

[ change the Background property by first selecting it ]

  1. With your Background property selected, click on the Gradient brush to specify a multi-color background fill:

[ a gradient brush allows you to use multiple colors ]

  1. Now that your Gradient brush has been selected, you'll see two gradient stops appear below your color Editor. In the color Editor, select a blue-ish color. Your second gradient stop will have been selected by default, and you will see your blue-ish color get applied to your gradient:

[ your second gradient stop is now a blue-ish color ]

  1. I kinda like having the black color displayed for the first gradient stop, so let's keep it as that. Your Artboard and your window should look like the following image:

[ notice the black->blue gradient ]

  1. Right now, our colors are moving in a left to right, horizontal direction. Let's change our gradient to move vertically instead. From your Toolbox, click on the Brush Transform button:

[ click on your Brush Transform button to change your gradient's orientation ]

  1. Once you have clicked on the Brush Transform button, the brush transform arrow will appear over your Window. Click on the tip of the arrow with your mouse cursor, and with your Ctrl and Shift keys pressed, drag your mouse down until the brush transform arrow points straight down:

[ rotate the tip of your Brush Transform arrow by dragging it down ]

  1. Ok, now we've spent enough time playing with our window's background color. Let's start adding our controls. Let's first add a control for taking our text input, and that control will be a Textbox. In your Toolbox, you'll see various groupings of controls. Find the Document/Text category, and the control that is already selected should be your Textbox. Simply double-click on that control's icon:

[ double-click on your Textbox ]

After you double-clicked on the TextBox control, a textbox will be added to your Window:

[ a new, default TextBox control is added ]

  1. Your newly added textbox is pretty generic. To modify it for this application, increase its width and height, and position it towards the left-center of your window as seen in the following image:

[ alter your textbox until it looks like what it shown in the above image ]

  1. You will see the default TextBox text displayed inside your textbox. Let's leave it there for now, because it gives you a good idea of what the text and its related font styles look like. As you can see, the text seems small when compared to the height of our textbox. Let's fix that.

    With your textbox selected, find the Text panel under Properties. The Font tab will be selected by default, and from that view, change the font size to something larger such as 16 or 18, and press the Bold button to bold the text:

[ increase the font size and click on the Bold button ]

Once you have made the above changes, notice that your default TextBox text inside your textbox looks much better:

[ what text contained inside your textbox looks like ]

  1. Alright - with our textbox's font size and style adjusted, we have no need for the default text. There are several ways of removing the default text. One way is by, with your textbox selected, finding the Common Properties panel and clearing any text located inside the Text property:

[ clear what is displayed inside your textbox by removing all text from the Text property ]

Once you have cleared your Text property, your textbox will become blank with no text displayed inside it:

[ your textbox no longer displays any text by default ]

  1. The final thing we are going to do is give our textbox a name. At the very top of your Properties panel, you'll see a textfield called Name. In that textfield, give your textbox the name textToSpeak:

[ give your textbox the name textToSpeak ]

  1. As of now, we have added a TextBox control for taking user input. What we need next is a way to submit that user input for further processing. That can be done using a button, so let's add one now. From your commonly used controls group in the Toolbox, find and select your Button control:

[ once you have selected your Button, its icon will be displayed ]

Double-click on the Button control to add a default button to your stage. Move and position your button to the right of your textbox as shown in the following image:

[ add your new button and place it to the right of the textbox ]

  1. With your button selected, let's give it a name. Just like before with our textbox, find the Name field and give your button the name speakButton:

[ give your button the name speakButton ]

  1. With the button's name taken care of, let's deal with the cosmetics. Now, our button is much shorter than our textbox. Let's resize our button by making it taller. When you resize your button, you'll notice that guide lines appear indicating that your button's height matches the height of your textbox:

[ use the guide lines to resize your textbox's height to that of your textbox ]

Using these guidelines, you can make sure your button's height matches the height of your textbox.

  1. Just like you adjusted the height of your button, increase the width of your button slightly also. Unlike before, you will not see any guide lines appear because there are no other objects in your vertical path for you to line up to. Simply use your best judgment:

[ resize your button horizontally a bit ]

  1. The final modification (for now) that we will do to our button is change its text from Button to Speak. With your button selected, find the Common Properties panel and change the Content property's value from Button to Speak:

[ change the default Content text from Button to Speak from the Common Properties panel ]

  1. The final UI related control we will add is our Label for displaying the what to say text. From your Toolbox, click on the Document/Text category in your toolbox to display a fly-out menu with controls related to using text:

[ expand the sub-group of Document/Text controls ]

  1. From this fly-out menu, select the Label control. As you see in the above picture, it is the second to last control displayed. Once you have selected your Label control, the icon for your Document/Text category will be the Label.

    Double-click on your Document/Text category, and since the Label is the selected control, a Label control will be added to your stage:

[ a default Label control has been added ]

  1. It's really hard to see our label control thanks to the dark text color on the dark background. With your label selected, find the Brushes panel and select the Foreground property:

[ let's change our label's foreground color by changing the Foreground property under Brushes ]

  1. With your Foreground property selected, in the Color Editor, select a light color. I have  picked a light gray color as seen in the following image:

[ choose a light color for the text that is visible over your window's dark background color ]

Once you have picked your lighter color for your Foreground, you will notice that your label's default Label text now becomes visible behind our dark window background:

[ your default Label text is now visible. Yay! ]

  1. Now that you can see the text that is visible, let's move it so that it is positioned just over the top-left of our textfield:

[ position your label near the top-left corner of our textfield ]

  1. Ok, with our text field positioned where you want it, let by replace the default Label text found in your label's Content property under Common Properties to say something instructive such as what to say:

[ replace the default Label text with what to say ]

  1. The last thing we'll do to our label is make the text stand out a bit. From the Text panel, increase the text size to something like 14 and click the Bold button to bold our text:

[ make the font size larger and Bold the text ]

After all of your changes have been made, your window will now look like the following image:

[ what your interface now looks like ]

Alright! You just created a very basic user interface for our application. We'll be revisiting our interface and making minor changes as our application is developed, so don't close Blend just yet!

Adding Our Application Logic
The application logic is the code that makes your application actually do something. So far, you've primarily focused on the user interface side of things. With the application logic, we delve into Visual Studio and C# with a dash of Blend here and there for building bridges between the designer and developer realms.

Binding an Event to an Event Handler
What we want to do is have our application read aloud the text you input into the textbox. That will be accomplished by you clicking on the Speak button. To do that, we need to add an event handler that does something when your Speak button is clicked.

In Blend, select your Speak button. From the Properties pane, to the right of your Name field and Properties button, you'll find the Events button:

[ click on the Events button to access tie events to event handlers ]

Click on the Events button to display a list of events your selected button supports. The first event listed should be the Click event:

[ the event we are interested in is the Click event ]

Click on the textfield to the right of the Click event to specify the name of your event handler. Give your event handler the name Speak:

[ in the Click event's textfield, enter the world Speak ]

Once you have given your event handler the name Speak, press Enter. After a brief second of what seems like frantic computer activity, Visual Studio / Express will launch. You may receive a security warning, and if you do, select the Load project normally option:

[ if prompted about opening a project created externally, choose the Load project normally option ]

The end result in most cases will be that you will see the event handler code snippet displayed for you in Visual Studio or Visual C# Express:

[ the Speak event handler has automatically been created for us ]

Great! In this section you bound an event to an event handler. To learn more about what that means, read my Event Handlers in WPF tutorial. To look at the end result, when somebody clicks on your Speak button, the Speak method (what you see in Visual Studio) will be called. Let's now proceed and look at how to make our Speak method actually say something out loud.

Adding Text-To-Speech Functionality
Since a large part of this tutorial is getting the existing text-to-speech functionality to work, you only have to add a few lines of code. Unlike previous tutorials where you could just copy and paste the code, resolve any missing namespaces, and test your application, this time around you have an extra step - adding a reference to the namespace that contains the Speech classes.

To see what I mean, replace all of the code found inside your namespace ItSpeaks section with the following:

public partial class Window1
{
private SpeechSynthesizer speech;
 
public Window1()
{
this.InitializeComponent();
 
// Insert code required on object creation below this point.
speech = new SpeechSynthesizer();
}
 
private void Speak(object sender, System.Windows.RoutedEventArgs e)
{
// Speak
speech.SpeakAsync(textToSpeech.Text);
 
// 0 to 100
speech.Volume = 100;
 
// -10 to 10
speech.Rate = -2;
}
}

Try building your application after having copied and pasted the above code. When you try to build, you will receive the following error: The type or namespace name 'SpeechSynthesizer' could not be found (are you missing a using directive or an assembly reference?):

[ you will receiving a missing reference error ]

Normally, you can just right click on your SpeechSynthesizer class, find the Resolve sub-menu, and add your missing namespace. When you try that, though, you are in for a bit of a surprise:

[ oh no - there is no Resolve sub-menu ]

Notice that there is no Resolve menu! In situations like this, you'll need to add a reference to the namespaces that contain the class you are looking for. That isn't overly difficult. The easiest way to determine which class SpeechSynthesizer belongs to is by searching MSDN (the huge MS repository of programming information) for SpeechSynthesizer.

In my search attempt, the very first result provided the information I needed:

[ the MSDN search results for our SpeechSynthesizer query ]

Notice that the SpeechSynthesizer Class is located in System.Speech.Synthesis namespace inside the System.Speech's system.speech.dll assembly. With this information, you can discern that you need to add a reference to something that contains System.Speech.

To add a reference, locate your Solution Explorer in your Visual Studio / Visual C# window. Find the References folder, right-click on it, and select Add Reference:

[ right click on the References folder and select the Add Reference menu item ]

Once you have selected Add Reference, the Add Reference window will appear. Click on the .NET tab and use the scrollbar to find the component named System.Speech:

[ add the System.Speech component from the Add Reference window ]

Once you have found and selected the System.Speech component, press OK. Your Add Reference window will disappear, and you will find that your Reference folder in your Solution now includes a reference to System.Speech:

[ System.Speech now appears among your References ]

Simply ensuring your System.Speech reference is added is not enough. You need to tell your code to use it. In Window1.xaml.cs - the file that should already been open, find the list of using statements towards the top of your code:

[ your current collection of using statements ]

It's time to add another using statement. Anywhere in that list, create a new line and type using System.Speech. By doing this, you ensure that your code will use the System.Speech namespace.

With your System.Speech namespace now recognized, in your code, right click on any instance of your SpeechSynthesizer text. Unlike before where you only saw the Refactor sub-menu, this time you will also see the Resolve sub-menu appear:

Use the Resolve menu and select the System.Speech.Synthesis path. If you try to build your project now, you should not receive an error. When you test your application, enter some text, and press the Speak button, you will hear what you wrote:

[ enter some text and click on the Speak button to hear text read aloud ]

We are almost done with the tutorial now. There is just one minor usability feature that we need to implement. In this application, to hear what you wrote, you need to use your mouse and click on the Speak button. Wouldn't it be more natural to simply use the Enter button after typing your text? I think so. Let's implement that feature in the next section.

Enter Button Functionality - IsDefault
There are several ways to implement playing back the text using the Enter button. The most common approach, the one you are probably most familiar with if you have a background in other language, is where you have a listener that detects when the Enter key on your keyboard was pressed. Once the listener detects the event, it will call the appropriate method to deal with the Enter key press. In WPF, there is an easier way when you have just one button.

In WPF, buttons have a property known as IsDefault. The IsDefault property allows you to call a button by simply pressing the Enter key. That is just what we want for our application, so let's set our Speak button's IsDefault property to true.

To do that, go back to Blend. Select your Speak button and make sure your button's properties are displayed by clicking on the Properties button:

[ click on the Properties button to access your button's properties ]

Under your button's properties, find the Common Properties panel. Contained in the Common Properties panel will be the IsDefault checkbox. Once you have found the IsDefault checkbox, click on it to check it:

[ check the IsDefault checkbox to set the property to true ]

If you test your application again, type a few words and press Enter. After you press Enter, you will hear your text played back audibly. Best of all, you didn't have to move your hand away from your keyboard to use the mouse to click on the Speak button like you had to earlier.


Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.

Your support keeps this site going! 😇

Kirupa's signature!

 

1 | 2 | 3 | 4




SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.