Text-to-Speech (TTS) is a technology that converts text into spoken words. It is a useful feature in a variety of applications, from virtual assistants to accessibility tools.
In addition, many funny and silly things can be done, such as bots for Discord, for Twitch, etc. 😅
Making TTS in C# is really straightforward. The System.Speech.Synthesis
library is part of the .NET Framework and provides basic TTS capabilities. It is easy to use and does not require external configurations.
In fact, it is so simple that Microsoft’s voice Helena is one of the most commonly used in TTS. You will recognize it immediately when you hear it in your program because it is used a lot.
For more information and detailed documentation, you can visit the following links System.Speech.Synthesis Documentation
TTS Implementation with System.Speech.Synthesis
System.Speech.Synthesis
is included in the .NET Framework, so there is no need to install any additional packages.
Let’s look at 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#");
}
}
So easy! Literally four lines and you have a working TTS.
Selecting a Voice
It is possible to configure different aspects of the synthesizer. Not too many, there isn’t much to “play” with.
But, as we have seen, it is possible to select the volume and the 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.");
}
}