转换并保存文本到语音文件
本文关键字:语音 文件 文本 保存 转换 | 更新日期: 2023-09-27 18:35:32
我正在使用此代码将文本转换为语音*使用系统.语音.合成;*但它抛出——异步操作只能在 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);
}
}
}
将其添加到页面加载中。
protected void Page_Load(object sender, EventArgs e)
{
System.ComponentModel.AsyncOperationManager.SynchronizationContext =
new System.Threading.SynchronizationContext();
}