Speech synthesis in .NET

Have you ever tried speech synthesis (i.e. text pronounced by computer)? It’s surprisingly easy.

The following trivial example announces the current time (language: PowerShell):

Add-Type -AssemblyName System.Speech
$synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
$synthesizer.Speak("It's {0:H m}" -f (Get-Date))

You can even make voice reporting of exceptions:

$nullReference.ToString()
trap
{
    Add-Type -AssemblyName System.Speech
    $synthesizer = New-Object -TypeName System.Speech.Synthesis.SpeechSynthesizer
    $synthesizer.SpeakAsync($_)
}

You should hear “You cannot call a method on a null-valued expression”, at least in English language environment. Notice also that the asynchronous call is used now.

Of course, much more complex scenarios are supported too, for example various voices, spelling, speech rate adjustments etc.  But the purpose of this post is just a brief demonstration, not going to details.

The last example is slightly more complex and hinting a possible “more useful” use. (The languahe is C#.)

using System.Speech.Synthesis;
 
PromptBuilder builder = new PromptBuilder();
builder.AppendText("Your number is");
builder.AppendBreak(TimeSpan.FromMilliseconds(200));
builder.AppendTextWithHint("1234567", SayAs.SpellOut);
 
builder.AppendBreak(TimeSpan.FromMilliseconds(500));
builder.AppendText("Thank you for your order.");
 
builder.AppendBreak(TimeSpan.FromMilliseconds(100));
builder.AppendText("Live long and prosper.");
 
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
synthesizer.Rate = -3;
synthesizer.Speak(builder);