Text-To-Speech Button

Posted on April 16, 2009. Filed under: .Net | Tags: , |

Recently, I stumbled upon the System.Speech.Synthesis namespace. It is located in the System.Speech.dll that comes with the .Net-Framework – for free! It offers a convenient way to read text to the user. Take this button as an example:

public class TTSButton: Button
{
    #region Text
 
    /// <summary>
    /// This is the text that should be read when the button is clicked
    /// </summary>
    public string TextToRead
    {
        get { return (string)GetValue(TextToReadProperty); }
        set { SetValue(TextToReadProperty, value); }
    }
    public static readonly DependencyProperty TextToReadProperty =
        DependencyProperty.Register("TextToRead", typeof(string), typeof(TTSButton), new UIPropertyMetadata());
    #endregion
 
    public TTSButton()
        : base()
    {
        this.Click += new RoutedEventHandler(TTSButton_Click);
    }
 
    /// <summary>
    /// Read the text to the user
    /// </summary>
    /// <param name="sender">The sender</param>
    /// <param name="e">The event</param>
    void TTSButton_Click(object sender, RoutedEventArgs e)
    {
        if (String.IsNullOrEmpty(this.TextToRead))
            return;
        SpeechSynthesizer s = new SpeechSynthesizer();
        s.SpeakAsync(this.TextToRead);
    }
}

The button gets its text from a dependency which enables binding, etc. The actual reading is done in just two lines of code! However, it is possible to customize the voice, e.g. by changing the speaker or the pace.

Advertisement

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.