Using System.Speech With .NET 7

In this article, I'll demonstrate how to use System.Speech.NET, a valuable tool for developing speech applications. It is available for .NET 4.x, .NET 5, 6, and 7.

It supports speech recognition and text-to-speech and provides a unified API.

With System.Speech.NET, you can easily create applications that understand and respond to natural language input.

We will focus here on the Speak method.

How do I do?

1) Create a folder and run dotnet command to create a new project,

Using System.Speech with Extension .NET 7

2) Open Manage NuGet Packages... on the context menu in "Dependencies" on Solution Explorer,

Using System.Speech with Extension .NET 7

3) Browse for System.Speech and add it to the project,

Using System.Speech with Extension .NET 7

4) Create an extension class,

using System.Speech.Synthesis;
namespace System;
public static class SystemSpeechExtension {
    const int PDefaultRate = 3;
    const int PErrorRate = 4;
    public static void Speak(this string text2speak) {
        text2speak.Speak(PDefaultRate);
    }
    public static void Speak(this string text2speak, int rate) {
        var voice = new SpeechSynthesizer();
        voice.SetOutputToDefaultAudioDevice();
        voice.Rate = rate;
        voice.Speak(text2speak);
    }
    public static void SpeakError(this string text2speak) {
        #if(DEBUG)
        $ "Error {text2speak} while debugging!".Speak(PErrorRate);
        #endif
    }
}

How to use this extension

Add controls to your Form.

Using System.Speech with Extension .NET 7

Add events

namespace WinFormsApp1;
public partial class Form1: Form {
    public Form1() {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e) => this.textBox1.Text.Speak();
    private void button2_Click(object sender, EventArgs e) => this.textBox1.Text.Speak(1);
    private void button3_Click(object sender, EventArgs e) {
        "Please, pay attention. Nothing is selected! Please, select an element.".Speak();
        try {
            var n = 0;
            var i = 0;
            var error = n / i;
        } catch (Exception ex) {
            ex.Message.SpeakError();
        }
    }
}

About the extension

Speak directly from the string like:

"Please, pay attention. Nothing is selected! Please, select an element.".Speak();     

Or from Text property,

this.textBox1.Text.Speak();

Bonus

While debugging, send speak from Message string error using SpeakError extension.

try {
    var n = 0;
    var i = 0;
    var error = n / i;
} catch (Exception ex) {
    ex.Message.SpeakError();
}

Extension methods are handy for working from value to action.

I hope this article helps you to make a better world.