Learn how to use the native Speech Synthesis of windows with .NET Framework 4.5

Speech synthesis with c# , make your app talk

The following code shows how to use Speech Synthesis in C#.

There is a global variable in the class called sintetizador , remember we need to include System.Speech.Synthesis.

This example uses the Async method and you'll learn how to execute the speech with listeners (start,end) without lock the UI. Read the summary of every function to more explanation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Synthesizer.net
{
    class SynthesizerUIHelper
    {
        private SpeechSynthesizer sintetizador = new SpeechSynthesizer();
        
        /// <summary>
        /// Speak a string of text asynchronously (without lock the ui). But we will add support for the events that it triggers.
        /// </summary>
        /// <param name="content"></param>
        public void speak(string content = "")
        {
            try
            {
                sintetizador.SelectVoice("Microsoft Irina Desktop"); // First list all the voices of the pc with <listAvailableVoicesConfigurator>
                sintetizador.SpeakProgress += new EventHandler<SpeakProgressEventArgs>(synthesizer_SpeakProgress);
                sintetizador.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(synthesizer_SpeakCompleted);
                sintetizador.SetOutputToDefaultAudioDevice();
                sintetizador.SpeakAsync(content);
            }
            catch (InvalidOperationException e) { Console.WriteLine(e.Message); }
        }

        private void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
        {
            Console.WriteLine("SpeakProgress: AudioPosition=" + e.AudioPosition + ",\tCharacterPosition=" + e.CharacterPosition + ",\tCharacterCount=" + e.CharacterCount + ",\tText=" + e.Text);
        }

        private void synthesizer_SpeakProgress(object sender, SpeakProgressEventArgs e)
        {
            Console.WriteLine("SpeakProgress: AudioPosition=" + e.AudioPosition + ",\tCharacterPosition=" + e.CharacterPosition + ",\tCharacterCount=" + e.CharacterCount + ",\tText=" + e.Text);
        }
        /// <summary>
        /// Stop the previous async speech
        /// </summary>
        public void stop()
        {
            try
            {
                sintetizador.SpeakAsyncCancelAll();
            }
            catch (ObjectDisposedException) { }
        }

        /// <summary>
        /// Set the sinthesizer volume with an integer (0 - 100)
        /// </summary>
        /// <param name="level"></param>
        public void setVolume(int level)
        {
            if (level > 100)
            {
                sintetizador.Volume = 100;
            }
            else if (level < 0)
            {
                sintetizador.Volume = 0;
            }
            else
            {
                sintetizador.Volume = level;
            }
        }

        public void resume()
        {
            sintetizador.Resume();
        }
        public void pause()
        {
            sintetizador.Pause();
        }

        /// <summary>
        /// Send speechSynthesizer output to a .wav file
        /// </summary>
        /// <param name="content"></param>
        public void toWAVFile(string content = "")
        {
            sintetizador.SelectVoice("Microsoft Irina Desktop");
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sintetizador.SetOutputToWaveFile(path + "/mySpokenAudio.wav");
            sintetizador.Speak(content);
            MessageBox.Show("File exported succesfully !",".wav File succesfully exported",MessageBoxButtons.OK,MessageBoxIcon.Information);
            sintetizador.SetOutputToDefaultAudioDevice();
        }
        
        /// <summary>
        /// Shows a list of all the voices available in the pc, note that you need to figure out a method to choose the voice in the previous functions.
        /// </summary>
        public void listAvailableVoicesConfigurator()
        {
            using (sintetizador)
            {
                foreach (InstalledVoice voice in sintetizador.GetInstalledVoices())
                {
                    var info = voice.VoiceInfo;
                    Console.WriteLine(info.name + " - " +info.Culture);
                }
            }

        }
    }
}

This github project is a simple app built with cefsharp and .NET Framework 4.5, a simple UI that allows you to choose a preinstalled voice of windows, talk,pause and display the progress of the speech in a progress bar, it's a good start to understand how the speech synthesis works.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors