如何在ASP.NET MVC中使用Windows语音合成器 - c#

我试图使用System.Speech类在ASP.NET mvc应用程序中生成语音。

[HttpPost]
public  ActionResult TTS(string text)
{
   SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
   speechSynthesizer.Speak(text);
   return View();
}

但是它给出了以下错误。

 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.

我在wpf应用程序中使用了System.Speech类和异步方法。

可以在ASP.NET mvc应用程序中使用System.Speech类吗?
怎么做?
<%@ Page Async="true" %>应该在哪里
放置?

参考方案

答案是:是的,您可以在MVC中使用System.Speech类。

我认为您可以尝试使用async控制器操作方法,并将SpeechSynthesizer.SpeakTask.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;
}

但是,如上例所示,生成的声音在服务器上播放,因为上面的代码在服务器端而不是客户端运行。要启用客户端播放,可以使用SetOutputToWaveFile方法并使用audio标记在返回下面示例中显示的视图页面时播放音频内容(假设您在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;
}

视图

<audio autoplay="autoplay" src="@Url.Content("~/path/to/file/" + ViewBag.FileName)">
</audio>

或者,您可以将操作类型更改为FileContentResult并将MemoryStreamSetOutputToWaveStream结合使用,以使用户自己播放音频文件:

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

参考:

Using Asynchronous Methods in ASP.NET MVC

类似问题:

How to use speech in mvc

System.Speech.Synthesis hangs with high CPU on 2012 R2

如何在ASP.NET Core Web应用程序中增加JSON反序列化MaxDepth限制 - c#

我们正在将ASP.NET Core 2.1与.NET Framework 4.6.2结合使用。我们有一个客户需要向我们的Web应用程序发送一个很大程度上嵌套的json结构。当他们进行此调用时,我们将输出以下日志并返回错误: 读取器的MaxDepth超过了32。路径“ super.long.path.to property”,第1行,位置42111。”我浏览了…

如何在ASP.NET MVC中的foreach内部脚本标记中 - javascript

                        这是我的日历代码:@section Scripts { @Scripts.Render("~/bundles/jqueryval") <script> $(document).ready(function () { $('#calendar').fullCal…

如何在ASP.NET Page_Load事件中识别RadButton启动回发的原因? - c#

在我的ASP.NET页的Page_Load中,我试图确定某个按钮是否已单击并尝试回发:if (Page.IsPostBack) { if (Request.Params.Get("__EVENTARGUMENT") == "doStuff") doSomething(); } doStuff是标记内的JavaScrip…

如何在ASP.NET Core角度Web应用程序中调用控制器的动作 - c#

我创建了一个ASP.NET Core角度项目。有angular的默认组件和mvc的HomeController。当我直接运行该应用程序时,它可以正常运行。网页显示了角度分量的输出。然后我看一下HomeController的源代码,如下所示:class HomeController { // ... some code here [HttpGet] publi…

如何在ASP.NET MVC中使用预定义设置创建.xml文件? - javascript

我有一个ASP.NET应用程序,可以从特定路径获取文件。目前,该路径在我的代码中是一个变量:string filePath = @"C:\FilesToWatch"; 现在我的实习老板说,现在我必须在.xml文件中预定义路径。我的问题是我在xml方面没有太多的经验,我也不知道该xml文件在项目中的存储位置。有没有例子或解决方案? 参考方案…