Monday, March 21, 2011

Speech Output with C#

The title probably sounds difficult, but in C# the realization of speech output can be done with only 2 lines of code.
This is, because the speech synthesis already known from Windows can also be used in the .Net framework, the needed component for that is the class System.Speech.Synthesis. To be able to use it, it first has to be included: Project - Add Reference - (Tab .Net) System.Speech. To simplify the code, we include it also via using:

using System.Speech.Synthesis;

For the speech output we need an instance of the class SpeechSynthesizer, which will output spoken text when the function Speak() is called.
But, of course there are also further properties, with which can be experimented.
A little overview:
 - Rate: Speed of the text output, ranges from -10 to 10
 - Volume: Volume, ranges from 0 - 100
 - Voice: Voice
The last property is read-only, but it can be changed with some functions.
Useful is the function SelectVoiceByHints(), which expects "hints" according to which a voice is selected. Such criteria are for example gender, age and even culture group.
The following command looks for a voice, which sounds female and grown up and sets this voice as new outout voice:

Speaker.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Adult);

However, on most Windows computers there will only be one preinstalled voice (at my computer for example only "Microsoft Anna"). Then the voice search does not have any influence.
A list of installed voices can be obtained via Speaker.GetInstalledVoices(). The single voices are represented as objects of the type Voice, the following example reads out all installed voices and adds them to the list InstalledVoices:

List<string> InstalledVoices = new List<string>();
foreach (InstalledVoice voice in Speaker.GetInstalledVoices())

No comments:

Post a Comment