Saving a Wave Stream on local disk after Speech Synthesizing

How do I write the "Hello World! Speech" text as a local disk .wav file? hellospeech.wav remains 0Ko. Where I'm wrong?

     SpeechSynthesizer synthesizer = new SpeechSynthesizer();
        MemoryStream waveStream = new MemoryStream();
        SpeechAudioFormatInfo synthFormat =  
            new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Stereo);
        string text = "Hello World! Speech";

        synthesizer.Speak(text);
        synthesizer.SetOutputToAudioStream(waveStream, synthFormat);
        synthesizer.SetOutputToNull();
        synthesizer.Dispose();

        string path = @"E:\hellospeech.wav";
        FileStream writeStream = new FileStream(path, FileMode.Create, FileAccess.Write); 
        int Length = 256;
        Byte[] buffer = new Byte[Length];
        int bytesRead = waveStream.Read(buffer, 0, Length); 
        while (bytesRead > 0)
        {
            writeStream.Write(buffer, 0, bytesRead);
            bytesRead = waveStream.Read(buffer, 0, Length);
        }
        waveStream.Close();
        writeStream.Close();
Jon Skeet
people
quotationmark

Two problems:

  • You're not rewinding the MemoryStream after saving to it
  • You're calling Speak before you set the output

You're also not using using statements - but that's not causing this issue.

I haven't used this SDK myself, but I'd expect this code to be more likely to work:

var waveStream = new MemoryStream();
using (var synthesizer = new SpeechSynthesizer())
{
    var synthFormat =  
        new SpeechAudioFormatInfo(44100, AudioBitsPerSample.Sixteen, AudioChannel.Stereo);
    string text = "Hello World! Speech";
    // Or SetOutputToWaveStream...
    synthesizer.SetOutputToAudioStream(waveStream, synthFormat);
    synthesizer.Speak("Hello World! Speech");
}

using (var file = File.Create(path))
{
    // With WriteTo, you don't need to rewind first...
    waveStream.WriteTo(file);
}

Is there any reason you're writing to a memory stream first though? Why not write straight to the file, for example using synthesizer.SetOutputToWaveFile(path)?

people

See more on this question at Stackoverflow