Speech synthesis in .NET, very easy!

ddanbe 5 Tallied Votes 557 Views Share

Thought it would be very complicated to include speech in your programs.
As it seems, in it most simplest form it can be done in two lines.
Don't forget to include the System.Speech reference in your References.
Enjoy!

using System;
using System.Speech.Synthesis;

namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
		//construct a message to say:
            var user = "Danny";
            var daypart = string.Empty;
            var now = DateTime.Now;
            if (now.Hour >= 6 && now.Hour <= 12)
            {
                daypart = " good morning";
            }
            else if (now.Hour > 12 && now.Hour <= 18)
            {
                daypart = " good afternoon";
            }
            else if (now.Hour > 18 && now.Hour <= 24)
            {
                daypart = " good evening";
            }
            var message = "Hello " + user + daypart;
			
			//start to speak
            var synth = new SpeechSynthesizer();           
            synth.Speak(message);
			
            Console.WriteLine(message);
            Console.ReadKey();
		}
	}
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

My only nitpick is a pet peeve in that SpeechSynthesizer implements IDisposable, which one should always respect:

using (var synth = new SpeechSynthesizer())
{
    synth.Speak(message);
}

It's ironic that MSDN's own examples typically don't respect IDisposable, despite the common occurrance of the following note variation on the same documentation page:

"Always call Dispose before you release your last reference to the SpeechSynthesizer. Otherwise, the resources it is using will not be freed until the garbage collector calls the SpeechSynthesizer object's Finalize method."

Then again, MSDN historically hasn't been a provider of good example code. ;)

commented: Good remark! +15
ddanbe 2,724 Professional Procrastinator Featured Poster

@decepticon: Remark very well appreciated! But does the garbage collector doesn't take care of that?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

But does the garbage collector doesn't take care of that?

The garbage collector takes care of memory for objects, but it doesn't know about internal resources allocated by the object. A good example is file handles. The garbage collector will clean up memory for a FileStream object, yet the file handle still needs to be closed.

A class implementation could put all of the cleanup code in the finalizer if there's no problem with waiting until the garbage collector gets around to cleaning up the object. The problem with that is that things like file handles should be disposed of as quickly as possible when you're done with them. That's what the IDisposable pattern is for: deterministic disposal of extraneous resources held by an object.

darkagn commented: Excellent description of garbage collection vs IDisposable +11
ddanbe 2,724 Professional Procrastinator Featured Poster

@deceptikon: Thanks again for this clarification.

johnrosswrock 0 Light Poster

Thank you for this program ...i have learnt a lot

ddanbe 2,724 Professional Procrastinator Featured Poster

Glad to be of help. :o)

JOSheaIV 119 C# Addict

Hmm, never knew this even existed, but then again that's programming for you. I might have to start using this, could be fun (especially for notifications where the occasional sound ... well I wouldn't want to use that boring thing)

Update: Ohh just started poking around MSDN for this library, I didn't realize you could tweak things like age and gender, I was expecting the good old Microsoft Sam voice (of course I still haven't heard it yet ... so that could drop me down a level of excitement)

ddanbe 2,724 Professional Procrastinator Featured Poster

@AngelofD4rkness: I have had the same experience with charting Did not know it existed either.

castajiz_2 35 Posting Whiz

The reference .Speech.Synthesis; does not exist in the library? How can i fix that

ddanbe 2,724 Professional Procrastinator Featured Poster

Just put System.Speech in your project References.
In your program include using System.Speech.Synthesis;

JOSheaIV 119 C# Addict

Hey just an FYI this can throw an error.

My sister broke my headset for my PC, so at the moment, I have no source of audio output hooked up to my PC. Well I ran a program where I was testing this function out and it threw an error cause I had no audio device.

Also, not sure what Charts are

ddanbe 2,724 Professional Procrastinator Featured Poster

There is surly a way to surpass this. Try-catch or the class has perhaps a method to detect if audio output is present. My code was just for demonstration purposes.
FYI it was my cat, who once destroyed my headset!!!

Charts are visual graphical representations of data. A barchart, the plot of a math function. This was my first attempt: Click Here

JOSheaIV 119 C# Addict

I just found it amusing it would throw an error with no audio output present (and my cat had started to mess up the headset my sister destroyed, but it wasn't very bad and didn't break it).

Hmm, this charting looks interesting

Siphokazi_F 0 Newbie Poster

I like this snippet it is quiet understandable, but how do you write it when you use ASP.NET c# empty web form? Do you have to create a class and code in it or just write in the page load method in the form class? Please reply thanks.

Gilberto_1 0 Newbie Poster

What kind of apps handles this? I created a Winforms app, instantiated the System.Speech but when I open the References folder it isn't there. I tried it many times and when I type the namespace (System.Speech.Synthesis) the Speech part is highlighted in red (not there). I know it isn't compatible with Web apps either and it I don't want to run this in a Console app. Thanks!

ddanbe 2,724 Professional Procrastinator Featured Poster

I also wanted to try out SpeechRecognition. I know it is possible, but apparently not on my machine with Windows 7 Home edition.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What version of the framework are you running in your project? This library was added in .NET 3.0.

ddanbe 2,724 Professional Procrastinator Featured Poster

My current version is 4.5 I have Speech, but I don't have SpeechRecognition.

kplcjl 17 Junior Poster

My version is Visual Studio 2010 Express. I believe that version is 4.0 but the express System Assembly does not include System.Speech.

Dang.

As far as the ASP.Net user, you are using the C# code to generate HTML and JScript (Looks exactly like JavaScript to me) to render on a web browser. The web definitely have sound generators but I don't know how to write it so the web can play it.

You can look to see if the synthesizer can write a file format of the sounds generated and if that file when linked on the web plays sounds, you may be able to play that on the web. All conjecture on my part.

Considering the error thrown when a sound bar doesn't exist, may be a bad conjecture.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.