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

我尝试使用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 . 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类和异步方法。

  1. 可以在ASP.NET mvc应用程序中使用System.Speech类吗?

  2. 怎么做?

  3. 应该在哪里放置

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

我想你可以尝试使用async控制器动作方法,并使用SpeechSynthesizer.SpeakTask.Run方法,如下所示:

 [HttpPost] public async Task TTS(string text) { Task 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 TTS(string text) { // you can set output file name as method argument or generated from text string fileName = "fileName"; Task 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; } 

视图

  

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

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

参考:

在ASP.NET MVC中使用异步方法

类似问题:

如何在mvc中使用语音

System.Speech.Synthesis在2012 R2上挂起了高CPU