Friday, December 17, 2010

WPF - Text to Speech in WPF

In this article i will show you how to convert text into speech.

Let see the example.

Step 1
Create a WPF Application.

Step 2
Desing the application,it is look like this


<Window x:Class="TextToSpeech.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Text to Speech" Height="350" Width="525" Background="Gray" WindowStartupLocation="CenterScreen">
    
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="393*" />
            <ColumnDefinition Width="110*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="10*" />
            <RowDefinition Height="51*" />
            <RowDefinition Height="201*" />
            <RowDefinition Height="39*" />
            <RowDefinition Height="10*" />
        </Grid.RowDefinitions>
        
        <TextBox x:Name="txtFileName" IsReadOnly="True" Grid.Column="0" Grid.Row="1" Height="23" Margin="5,0"></TextBox>
        <Button x:Name="btnOpenFile" Content="Open" Grid.Column="1" Grid.Row="1" Height="40" Margin="5,0" Click="btnOpenFile_Click"></Button>
        
        <RichTextBox x:Name="rtxtContent" Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" Margin="5,0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"></RichTextBox>

        <Button x:Name="btnSpeech" Grid.Column="1" Grid.Row="3" Content="Voice"  Margin="5,5,5,0" Click="btnSpeech_Click"></Button>
    </Grid>
</Window>

Step 3

Add two assembly reference to the project.
  1. System.Window.Forms
  2. System.Speech
Right click on the project name in Solution Explorer, select Add Reference and select System.Window.Forms and System.Speech on the .NET Tab and select OK button.




Click on image for better view

Step 4
Create a FileHandling static class for open a file dialog box and you can open browse a text file. After that it reads the text file and opens it in the RichTextBox control,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TextToSpeech
{
    public static class FileHandling
    {
        #region Methods

        /// <summary>
        /// Open file dialog box and open a file
        /// </summary>
        /// <returns>String</returns>
        public static String OpenFile()
        {
            String FileName = String.Empty;
            try
            {
                System.Windows.Forms.OpenFileDialog OFDObj = new System.Windows.Forms.OpenFileDialog();

                OFDObj.Filter = "Text files (*.txt)|*.txt";
                OFDObj.RestoreDirectory = true;

                if (OFDObj.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    FileName = OFDObj.FileName; // return full file path
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return FileName;
        }

        /// <summary>
        ///  Load Contents of file into RichText Box control
        /// </summary>
        /// <param name="FilePath">Specify the File Path</param>
        /// <param name="RichTextBoxObj">Specify RichTextBox Control Object</param>
        public static void LoadFile(String FilePath,System.Windows.Controls.RichTextBox RichTextBoxObj)
        {
            try
            {

                System.Windows.Documents.TextRange Range=null;

                System.IO.FileStream fStream = null; ;

                if (System.IO.File.Exists(FilePath))
                {

                    Range = new System.Windows.Documents.TextRange(RichTextBoxObj.Document.ContentStart, RichTextBoxObj.Document.ContentEnd);

                    fStream = new System.IO.FileStream(FilePath, System.IO.FileMode.OpenOrCreate);

                    Range.Load(fStream, System.Windows.DataFormats.Text);

                    fStream.Close();

                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        /// <summary>
        ///  Convert Rich text box contents into String
        /// </summary>
        /// <param name="RichTextBoxObj">Specify RichTextBox Control Object</param>
        /// <returns>String</returns>
        public static String ConvertRichTextBoxToString(System.Windows.Controls.RichTextBox RichTextBoxObj)
        {
            try
            {
                System.Windows.Documents.TextRange Range = new System.Windows.Documents.TextRange(RichTextBoxObj.Document.ContentStart,RichTextBoxObj.Document.ContentEnd);

                return Range.Text;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion

        
    }
}


Step 5
Create a TextToSpeechLib static class for convert text into speech,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;

namespace TextToSpeech
{
    public static class TextToSpeechLib
    {
        #region Declaration

        private static SpeechSynthesizer Speech = null;

        #endregion

        #region Methods

        /// <summary>
        ///  Speak the Specified Text
        /// </summary>
        /// <param name="Text">Specify the Contents</param>
        public static void Voice(String Text)
        {
            try
            {
                Speech = new SpeechSynthesizer();
                Speech.SpeakAsync(Text); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        /// <summary>
        /// Pause the voice
        /// </summary>
        public static void VoicePause()
        {
            try
            {
                Speech.Pause(); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        /// <summary>
        /// Resume the voice
        /// </summary>
        public static void VoiceResume()
        {
            try
            {
                Speech.Resume(); 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }
        }

        #endregion
    }
}

Step 6
Add the below code in btnOpen button click event handler.it is look like this

private void btnOpenFile_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtFileName.Text = FileHandling.OpenFile(); // open a file.
 
                if(txtFileName.Text !=String.Empty)
                {
                    FileHandling.LoadFile(txtFileName.Text, rtxtContent); // load the file contents into RichTextBox Control
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);   
            }
        }

Step 7
Add the below code in btnSpeech button click event handler.it is look like this

 private void btnSpeech_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                String Text = FileHandling.ConvertRichTextBoxToString(rtxtContent);

                if (Text.Trim()!=String.Empty ) 
                {
                    switch (btnSpeech.Content.ToString())
                    {
                        case "Voice": // Speak the specified text

                            TextToSpeechLib.Voice(Text);
                            btnSpeech.Content = "Pause";

                            break;

                        case "Pause": // Pause the voice

                            TextToSpeechLib.VoicePause();
                            btnSpeech.Content = "Resume";
                            break;

                        case "Resume": // Resume the voice

                            TextToSpeechLib.VoiceResume();
                            btnSpeech.Content = "Pause";

                            break;
                    }
                }
                else
                {
                    MessageBox.Show("Content is blank");  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }


Run the project.

Download
Download Source Code

No comments:

Post a Comment