Search code examples
c#speechspeechsynthesizer

How can I interrupt playing of text to speech synthesis in my application?


This is the code that I used to speech a richTextBox. My problem is that I can't click on anything when the text is playing. I can't even stop playing. How can I fix the problem? Is there any way to stop playing by clicking on a button?

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

Solution

  • The problem is that the Speak() method is Synchronous, so it will lock the thread you're on. Assuming you're on a single thread, that will be the UI thread, thus locking anything you're doing.

    You might perhaps be better using a different thread to Speak(), which won't lock your current (UI) thread.

    SpeechSynthesizer.Speak Method (String) - MSDN

    Or you can use the SpeechAsync method, which will do it asyncronously!

    SpeechSynthesizer.SpeakAsync Method (String) - MSDN