Text To Speech in C# (with Talking Browser!) - ' Adding Speech ' (
Page 2 of 2 )
Adding Speech
The next thing to do is add the speech capability. Step one in the process is to add a reference to the SAPI COM object. In Visual Studio's Solution Explorer window, right click on the References folder and select Add Reference. In the dialog that appears, select the COM tab and find Microsoft Speech Object Library as shown below.
Once the reference has been added, you can declare and instantiate an object as follows.
SpeechLib.SpVoiceClass m_TTS = new SpeechLib.SpVoiceClass();
Using the speech object is simple. You can make it say Hello World with the following code.
m_TTS.Speak("Hello World",
SpeechLib.SpeechVoiceSpeakFlags.SVSFDefault);
That works fine if you are willing to have your code wait until SAPI is done speaking the text. But if you want to kick off the text to speech process and continue with what you need to do while it's speaking, you'll need the Speak method to be asynchronous. To do this, all you need to do is change the flag from SVSFDefault to SVSFFlagsAsync as the following code shows.
m_TTS.Speak("Hello World",
SpeechLib.SpeechVoiceSpeakFlags.SVSFFlagsAsync);
There is one last thing to consider with regards to the Speak method. The asynchronous calls add speech to a queue. If you made ten consecutive calls to the Speak method, then SAPI would talk for awhile until it was done. Many times you'll want to clear the queue before it starts speaking again. There's a flag that you can add to the SVSFFlagsAsync flag, it's the SVSFPurgeBeforeSpeak flag as shown below.
m_TTS.Speak("Hello World",
SpeechLib.SpeechVoiceSpeakFlags.SVSFFlagsAsync |
SpeechLib.SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
The program needs to start speaking once the page has been downloaded. The web browser object has an event that can fire when the document download is complete. It can be added from the properties window as long as the event selector (denoted by the lightning bolt icon) is selected as shown below.
I added an event handler to the demonstration program named OnDocumentCompleted. This method gets the innerText property from the document and kicks off the speech. The method can be seen below.
// This is fired once the document download is complete.
private void OnDocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
// Get the document inner text.
string strPageText = objWebBrowser.Document.Body.InnerText;
// Call the speech object's
// Speak method.
m_TTS.Speak(strPageText,
SpeechLib.SpeechVoiceSpeakFlags.SVSFlagsAsync |
SpeechLib.SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
}
The speech object has quite a few methods that you can use to modify the speech properties. The Voice and Volume properties are the ones I use most often.
Conclusion
As you can see, both creating custom web browsers and adding speech to applications are easy tasks. Adding speech to your applications can give it the edge it needs.