Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A Text to WAV Converter

3.94/5 (12 votes)
7 Aug 2005CPOL3 min read 1   1.8K  
Makes use of Windows Forms and the Speech API to create WAV files from text
Sample Image - Main Window.jpg

Introduction

Normally, you would create a document using something like Microsoft Word or Notepad. Providing it follows certain formatting conventions, it should be accessible to most people. However, what would you do if you are creating something that might need to be accessed by the partially sighted or blind?

It would be either difficult or impossible to convey something using text. With this program, you can convert a text file, or something you type in the program's text area, into WAV audio so the information it contains can also be heard.

Background

To achieve this program's goal, you need to make use of the Speech API and I have chosen to use it in conjunction with C#. While the voice produced may have its limitations, the most important thing is the information contained in the original text. If the text is not suitable, then no amount of improvements to the converter can make the file that's produced more useful.

The Source Code

Finding a Text File to Convert

The first stage. As I stated in the introduction, you can convert anything you type in the program's text area, but there are limited capabilities here so it might be better to use an external program to create a text file.

C#
private void Browse_Click(object sender, EventArgs e)
    {
        string fileName;
        OpenFileDialog OpenFile = new OpenFileDialog();
        
        try 
        {
            OpenFile.CheckFileExists = true;
            OpenFile.CheckPathExists = true;
            OpenFile.DefaultExt = "txt";
            OpenFile.DereferenceLinks = true;
            OpenFile.Filter = "Text files (*.txt)|*.txt|" +    
				"RTF files (*.rtf)|*.rtf|" + 
                              "Word Documents (*.doc)|*.doc|" +    
				"Works 6 and 7 (*.wps)|*.wps|" + 
                              "Windows Write (*.wri)|*.wri|" + 
				"WordPerfect document (*.wpd)|*.wpd";
            OpenFile.Multiselect = false;
            OpenFile.RestoreDirectory = true;
            OpenFile.ShowHelp = true;
            OpenFile.ShowReadOnly = false;
            OpenFile.Title = "Select a file to convert";
            OpenFile.ValidateNames = true;

            if (OpenFile.ShowDialog() == DialogResult.OK)
            {
                fileName = OpenFile.FileName;
                StreamReader sr = new StreamReader(OpenFile.OpenFile());
                aText.Text = sr.ReadToEnd();
            }
        }
        catch
        {
            MessageBox.Show("Something is wrong here", "Text2Audio");
        }
        finally
        {
            if(sr != null)
            {
                sr.Close();
            }
        }
    }

When dealing with filestreams, it is essential you use a try-catch, with an optional finally. This means you can minimize problems at runtime caused by e.g. files being corrupted. While I have used a rather trivial and ambiguous error message in the catch section, it will be better to make this more specific if you were to create this for an average user. Having a message that is either too technical or too ambiguous will only limit the possible audience.

Converting to Audio

C#
private void Convert_Click(object sender, EventArgs e)
    {
        SaveFileDialog cfile = new SaveFileDialog();

        try 
        {
            SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
            SpVoice speech = new SpVoice();
            cfile.Filter = "wav files (*.wav)|*.wav";
            cfile.Title = "Save to a wave file";
            cfile.FilterIndex = 2;
            cfile.RestoreDirectory = true;
            if (cfile.ShowDialog()== DialogResult.OK) 
            {
                SpeechStreamFileMode SpFileMode = 
			SpeechStreamFileMode.SSFMCreateForWrite;
                SpFileStream SpFileStream = new SpFileStream();
                SpFileStream.Open(cfile.FileName, SpFileMode, false);
                speech.AudioOutputStream = SpFileStream;
                speech.Speak(aText.Text, SpFlags);
                speech.WaitUntilDone(Timeout.Infinite);
                SpFileStream.Close();
            }
        }
        catch
        {
            MessageBox.Show("Something's gone wrong here.");
        }
        MessageBox.Show("Conversion successful!", "Text2Audio");
    }

This is perhaps the most complicated bit of the process. While the filestreaming here isn't difficult (because we used the reverse of this earlier), the conversion to audio is. Again, you must make use of the try-catch facility to minimize problems.

This method sets the audio output stream as the filestream that we created. I have also made use of threading so this section stops when the conversion is complete and never earlier than that. It would be pointless if it only turned half the text into a WAV file!

Points of Interest

Perhaps the most annoying thing about the Speech API is the voice. It has severe limitations and does things such as saying 'bracket', instead of just changing the emphasis. This could perhaps be improved by doing some automated alterations to the text before it is sent to be converted. Also, there is only one voice, which limits the program to those of us who speak English.

Suggestions

I will be happy to accept any suggestions for improvements to this code. All you have to do is send them to my email address and I will reply as soon as possible.

Use of this Project

Please note that if you want to use any part of this code in one of your own projects/solutions, you are free to do so providing you include a comment stating that it was me who created the code, my email address and also put where you got it from.

This is completely open-source. If you would like to use any of this for a commercial project, then you must send me an email with a request and I will decide whether I will allow you to go ahead. Any emails sent to me will be read and replied to as quickly as possible.

History

  • 7th August, 2005 - First edition of the program

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)