在SpeechSynthesizer类实例停止发言后关闭表单

时间:2014-04-09 15:00:35

标签: c# forms events speechsynthesizer

所以,我正在使用SpeechSynthesizer类来创建音频文本阅读器。 当语音开始说话时,我想显示一个带有消息的表单 像“等待,正在阅读文本”,按钮“Stop Reading”)。 如果用户单击该按钮,则应停止文本读取。如果用户没有单击该按钮,则表单必须在读完整个文本后自动关闭。

我面临的问题是,当说话停止时,我不知道如何抓住那一刻,我不知道何时或如何关闭表格。

也许最好使用MessageBox,但没关系,我会想到一些事情。 主要问题是我不知道何时关闭它。 我希望我能说清楚,先谢谢你。

我还没有在表格中添加任何按钮......

    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.
    }

1 个答案:

答案 0 :(得分:2)

您需要将表单变量设为Class级变量,并订阅SpeakCompleted事件并使用SpeakAsync方法。

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();
    }
}