csharp-generar-voz-tts

How to Implement Text-to-Speech (TTS) in C#

  • 2 min

Text-to-Speech (TTS) is a technology that converts text into spoken speech. It’s a useful feature in a variety of applications, from virtual assistants to accessibility tools.

Besides, you can do many funny and silly things, like bots for Discord, for Twitch, etc. 😅

Doing TTS in C# is really simple. The System.Speech.Synthesis library is part of the .NET Framework and provides basic TTS capabilities. It’s easy to use and doesn’t require external configurations.

In fact, it’s so simple that Microsoft’s Helena voice is one of the most used in TTS. You’ll recognize it immediately when you hear it in your program, because it’s used a lot.

Implementing TTS with System.Speech.Synthesis

System.Speech.Synthesis is included in the .NET Framework, so no additional package installation is necessary.

Let’s see a simple example of how to use System.Speech.Synthesis to convert text to speech:

using System;
using System.Speech.Synthesis;

class Program
{
    static void Main(string[] args)
    {
        // Create an instance of the synthesizer
        SpeechSynthesizer synthesizer = new SpeechSynthesizer();

        // Configure the synthesizer (optional)
        synthesizer.Volume = 100;  // 0...100
        synthesizer.Rate = 0;      // -10...10

        // Convert text to speech
        synthesizer.Speak("Hello, welcome to the Text-to-Speech tutorial in C#");

        // Or, to speak asynchronously
        // synthesizer.SpeakAsync("Hello, welcome to the Text-to-Speech tutorial in C#");
    }
}
Copied!

It’s that simple! Literally four lines and you have a working TTS.

Selecting a Voice

It’s possible to configure different aspects of the synthesizer. Not too many, there isn’t much to “play” with.

But, as we’ve seen, it is possible to select the volume and speed, as well as select a specific voice:

using System.Speech.Synthesis;

class Program
{
    static void Main(string[] args)
    {
        SpeechSynthesizer synthesizer = new SpeechSynthesizer();

        // List available voices
        foreach (InstalledVoice voice in synthesizer.GetInstalledVoices())
        {
            VoiceInfo info = voice.VoiceInfo;
            Console.WriteLine("Voice Name: " + info.Name);
        }

        // Select a specific voice
        synthesizer.SelectVoice("Microsoft Helena Desktop");

        synthesizer.Speak("This is a test with a specific voice.");
    }
}
Copied!