Question

So, I'm using SpeechSynthesizer class to create an audio text reader. When the voice starts to speak I want to display a form with a message saying smth like "Wait, text is being read", with button 'Stop Reading'). If a user clicks the button, the text reading should stop. If user doesn't click the button, then the form must close automatically after the whole text has been read.

The problem that I'm facing is that I don't know how to catch that moment when the speak is stopped, I don't know when or how to close the form.

Maybe it's better to use MessageBox, but it doesn't matter, I'll think of something. The main problem is that I don't know when to close it. I hope I made myself clear, thank you in advance.

I haven't added any button to the form yet...

    private void Play_Click(object sender, EventArgs e)
    {
        string textToRead;

        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
        synthesizer.Volume = trackBarVolume.Value; // 0...100
        synthesizer.Rate = trackBarSpeed.Value; // -10...10

        textToRead = richTexBoxinput.Text;

        richTexBoxinput.Text = "";


        synthesizer.SpeakStarted += speakStarted;

        synthesizer.Speak(textToRead);
    }

    static void speakStarted(object sender, SpeakStartedEventArgs e)
    {
        Form form = new Form();
        Label label = new Label();
        label.Text = "Please wait, the text is being read";
        form.Controls.Add(label);

        form.Show();
        // I need to close this form after finishing the speak.
    }
Was it helpful?

Solution

You need to make your form variable a Class level variable, and subscribe to the SpeakCompleted event and use the SpeakAsync Method.

public partial class Form1 : Form
{
    Form frm;  //Note class level declaration
    public Form1()
    {
        InitializeComponent();
    }

    private void Play_Click(object sender, EventArgs e)
    {
        string textToRead;

        SpeechSynthesizer synthesizer = new SpeechSynthesizer();
        synthesizer.Volume = trackBarVolume.Value; // 0...100
        synthesizer.Rate = trackBarSpeed.Value; // -10...10

        textToRead = richTexBoxInput.Text;

        richTexBoxInput.Text = "";


        synthesizer.SpeakStarted += speakStarted;
        synthesizer.SpeakCompleted += synthesizer_SpeakCompleted;

        synthesizer.SpeakAsync(textToRead);  //Using SpeakAsync so that SpeakCompleted event will be shown

    }

    private void speakStarted(object sender, SpeakStartedEventArgs e)
    {
        frm = new Form();
        Label label = new Label();
        label.Text = "Please wait, the text is being read";
        frm.Controls.Add(label);
        frm.Show();

    }

    void synthesizer_SpeakCompleted(object sender, SpeakCompletedEventArgs e)
    {
        frm.Close();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top