2

这是我用来演讲richTextBox 的代码。我的问题是播放文本时无法单击任何内容。我什至无法停止播放。我该如何解决这个问题?有什么方法可以通过单击按钮停止播放?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Speech.Synthesis;

namespace Merger
{
    public partial class Form1 : Form
    {
        SpeechSynthesizer tell = new SpeechSynthesizer();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.SelectionAlignment = HorizontalAlignment.Center;

            tell.Rate = trackBar1.Value;
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            tell.Volume = 100;
            tell.Speak(richTextBox1.SelectedText);
        }

        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            tell.Rate = trackBar1.Value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            tell.SpeakAsyncCancelAll();
        }
    }
}
4

1 回答 1

3

问题是该Speak()方法是同步的,所以它会锁定你所在的线程。假设你在一个线程上,那将是 UI 线程,从而锁定你正在做的任何事情。

您可能会更好地使用不同的线程Speak(),它不会锁定您当前的(UI)线程。

SpeechSynthesizer.Speak 方法(字符串) - MSDN

或者您可以使用 SpeechAsync 方法,它会异步执行!

SpeechSynthesizer.SpeakAsync 方法(字符串) - MSDN

于 2014-03-25T17:28:18.000 回答