Text-Speech from a file in C#.Net

Monday, March 2, 2009

I’ve just started doing some programming in C# using the .NET framework since it’s a requirement for my final year project. In this post, I shall show how to read out loud the contents of a file stored in any drive. I’m doing this on Microsoft Vista SP1  so it already has all the speech APIs as the speech SDK 5.3 is already inbuilt in Vista. In case you’re doing it on Windows XP, you’ll probably need to download the speech SDK from Microsoft Downloads site. However, the latest version for download is 5.1 I think, definitely not 5.3.

So, open a C# console application in Visual Studio 2008. I’ve already created a file called text.txt in the drive named X. This can read a text file stored in a pen drive also.

In the Solution Explorer on right hand side, right click References. In the Add Reference, select System.Speech from .NET tab and click ok. Add namespace System.Speech and System.Speech.Synthesis as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Speech; // required for speech utilities
using System.Speech.Synthesis; // required for speech utilities
namespace ConsoleApplication1
{ 
    class Program
    {
        static void Main(string[] args)
        {
           //Create an instance of class SpeechSynthesizer 
           SpeechSynthesizer cerra = new SpeechSynthesizer();           
          //ReadAllText opens the file, reads all content and closes it. The output of this needs to be converted to string and given to cerra
           cerra.Speak(File.ReadAllText"X:/text.txt").ToString());            
        }       
    }
}


The above can read only text files as of  now. It does not work with DOC files and encoding comes into picture here, so trying to figure that out yet. However, in the next post let us make cerra read out the results of a query from a SQL server database. Till then signing off… Au Revoire.




3 comments:

Unknown said...

nice to see you in the project mode..all the very best.

NR said...

lol...not ma cup of tea!!

All the best for your project

Joe said...

Thanks a lot. I used this code
for a console video game i was programming and it worked great.

 
Design by Pocket