语音合成后在本地磁盘上保存 Wave Stream

Saving a Wave Stream on local disk after Speech Synthesizing

如何将 "Hello World! Speech" 文本写入本地磁盘 .wav 文件? hellospeech.wav 仍然是 0Ko。我哪里错了?

     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();

两个问题:

  • 您没有在保存 MemoryStream 后倒带
  • 您在设置输出
  • 之前调用Speak

您也没有使用 using 语句 - 但这不是导致此问题的原因。

我自己没有使用过这个 SDK,但我希望这段代码更有可能工作:

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);
}

你有什么理由先写入内存流吗?为什么不直接写入文件,例如使用 synthesizer.SetOutputToWaveFile(path)?