SpeechSynthesizer in ASP.NET - async error

僤鯓⒐⒋嵵緔 提交于 2020-01-13 20:22:10

问题


I would like to be able to generate speech in my ASP.NET app by calling speak.aspx?text=Hello%20world. This would give a response in .wav format.

So far I have a blank page with code behind:

protected void Page_PreRender(object sender, EventArgs e)
{
  using (var ss = new SpeechSynthesizer()) {
    MemoryStream str = new MemoryStream();
    ss.SetOutputToWaveStream(str);
    ss.Speak(Server.UrlDecode(Request.QueryString["text"]));
    Response.AddHeader("Content-Type", "audio/wav");
    str.WriteTo(Response.OutputStream);
    str.Close();
  }
}

However this fails with message:

InvalidOperationException: Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event.

If I add Async="true" to the @Page directive, the code runs but a request for the page hangs indefinitely. Please could you let me know what's wrong, and show the correct code/approach to use?

Note I can't just use the Google text-to-speech API since it only allows strings of 100 characters or less.

Thank you.


回答1:


You should probably move the code above into the page_load method. there's no real reason for doing what you're doing in prerender.

If you make the page async, then you need to change your programming style. see if this helps:

Example of Asynchronous page processing in ASP.net webforms (.NET 2.0)



来源:https://stackoverflow.com/questions/7674482/speechsynthesizer-in-asp-net-async-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!