Search code examples
c#systemtext-to-speech

How do i get the EventHandler(SpeakCompleted) in C# to work? (System.Speech)


Simply put, I want to make a program that counts down (+ voice) but when numbers like 1mil comes this takes longer than 1 sec to pronounce so I would like to find out how I can get the "EventHandler" to run and how I can use it (i do not need code for counting etc. but how to create an EventHandler and where i need to write the Code when its been called)

https://learn.microsoft.com/en-us/dotnet/api/system.speech.synthesis.speechsynthesizer.speakcompleted?view=netframework-4.8

I cant just use Text.Speak("") cuz this leads to desync with the Text printed. I need that callback to start a new Speak and sync it with Text.

Sry... i hate to ask ppl but after 3h i surrender pls help me

        SpeechSynthesizer synth = new SpeechSynthesizer();
        int counting = 0;
        private void TTS() //First trigger
        {
            synth.SetOutputToDefaultAudioDevice();
            synth.SelectVoiceByHints(VoiceGender.Female, VoiceAge.NotSet, 0);
            textBox1.Text = "1";
            synth.Speak("1");
            counting = 1;
            synth.SpeakCompleted += synth_SpeechOver;
        }
        //public event EventHandler<System.Speech.Synthesis.SpeakCompletedEventArgs> SpeakCompleted; deleted
        public void synth_SpeechOver(object sender, EventArgs e)
        {
            synth.SetOutputToDefaultAudioDevice();
            synth.SelectVoiceByHints(VoiceGender.Female, VoiceAge.NotSet, 0);
            counting++;
            synth.Speak(counting.toString());
        }
        void Form1_SpeakCompleted(object sender, EventArgs e)
        {

        }
        //(Form1_SpeakCompleted is just for testing (doesnt work)

Solution

  • Callback only works for SpeakAsync

    https://learn.microsoft.com/en-us/dotnet/api/system.speech.synthesis.speechsynthesizer.speakcompleted?view=netframework-4.8

    The SpeechSynthesizer raises the SpeakCompleted event at the completion of any of the SpeakAsync or SpeakSsmlAsync methods.