Kab*_*esh 2 c# asp.net-mvc async-await system.speech.recognition
我试图使用System.Speech该类在ASP.NET mvc应用程序中生成语音。
[HttpPost]
public ActionResult TTS(string text)
{
SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
speechSynthesizer.Speak(text);
return View();
}
Run Code Online (Sandbox Code Playgroud)
但是它给出了以下错误。
System.InvalidOperationException: 'An asynchronous operation cannot be
Started at this time. Asynchronous operations may only be started within an
asynchronous handler or module or during certain events in the Page lifecycle.
If this exception occurred while executing a Page, ensure that the Page is
marked <%@ Page Async="true" %>.
This exception may also indicate an attempt to call an "async void" method,
which is generally unsupported within ASP.NET request processing. Instead,
the asynchronous method should return a Task, and the caller should await it.
Run Code Online (Sandbox Code Playgroud)
我在wpf应用程序中使用了System.Speech类和异步方法。
可以在ASP.NET mvc应用程序中使用System.Speech类吗?
怎么做?
<%@ Page Async="true" %>放在哪里?答案是:是的,您可以System.Speech在MVC中使用类。
我认为您可以尝试使用async控制器操作方法并SpeechSynthesizer.Speak与以下Task.Run方法一起使用:
[HttpPost]
public async Task<ActionResult> TTS(string text)
{
Task<ViewResult> task = Task.Run(() =>
{
using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
{
speechSynthesizer.Speak(text);
return View();
}
});
return await task;
}
Run Code Online (Sandbox Code Playgroud)
但是,如上例所示,生成的声音在服务器上播放,因为上面的代码在服务器端而不是客户端运行。要启用在客户端播放,可以在返回下面显示的视图页面时使用SetOutputToWaveFilemethod和使用audiotag播放音频内容(假设您在CSHTML视图中使用HTML 5):
控制者
[HttpPost]
public async Task<ActionResult> TTS(string text)
{
// you can set output file name as method argument or generated from text
string fileName = "fileName";
Task<ViewResult> task = Task.Run(() =>
{
using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
{
speechSynthesizer.SetOutputToWaveFile(Server.MapPath("~/path/to/file/") + fileName + ".wav");
speechSynthesizer.Speak(text);
ViewBag.FileName = fileName + ".wav";
return View();
}
});
return await task;
}
Run Code Online (Sandbox Code Playgroud)
视图
<audio autoplay="autoplay" src="@Url.Content("~/path/to/file/" + ViewBag.FileName)">
</audio>
Run Code Online (Sandbox Code Playgroud)
或者,你可以改变动作类型FileContentResult和使用MemoryStream与SetOutputToWaveStream让用户播放音频文件自己:
Task<FileContentResult> task = Task.Run(() =>
{
using (SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer())
{
using (MemoryStream stream = new MemoryStream())
{
speechSynthesizer.SetOutputToWaveStream(stream);
speechSynthesizer.Speak(text);
var bytes = stream.GetBuffer();
return File(bytes, "audio/x-wav");
}
}
});
Run Code Online (Sandbox Code Playgroud)
参考:
类似问题:
System.Speech.Synthesis在2012 R2上的高CPU挂起
| 归档时间: |
|
| 查看次数: |
2286 次 |
| 最近记录: |