0

我正在使用此代码 使用 System.Speech.Synthesis将文本转换为语音并将其保存为语音;* 但它会抛出 - 异步操作只能在 PreRenderComplete 事件之前的页面上启动。这是我的代码:

using (Stream ret = new MemoryStream())
        using (SpeechSynthesizer synth = new SpeechSynthesizer())
        {
            var mi = synth.GetType().GetMethod("SetOutputStream", BindingFlags.Instance | BindingFlags.NonPublic);
            var fmt = new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Eight, AudioChannel.Mono);
            mi.Invoke(synth, new object[] { ret, fmt, true, true });
            synth.Speak("Greetings from stack overflow");
            // Testing code:
            using (var fs = new FileStream(@"c:\temp\test.wav", FileMode.Create, FileAccess.Write, FileShare.None))
            {
                ret.Position = 0;
                byte[] buffer = new byte[4096];
                for (; ; )
                {
                    int len = ret.Read(buffer, 0, buffer.Length);
                    if (len == 0) break;
                    fs.Write(buffer, 0, len);
                }
            }
        }
4

1 回答 1

0

将此添加到页面加载中。

protected void Page_Load(object sender, EventArgs e)
{
    System.ComponentModel.AsyncOperationManager.SynchronizationContext =
        new System.Threading.SynchronizationContext();
}
于 2014-01-24T03:06:36.003 回答