C# 如何在ASP.NET MVC中使用windows语音合成器

C# 如何在ASP.NET MVC中使用windows语音合成器,c#,asp.net-mvc,async-await,system.speech.recognition,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(); } 但它给出了以下错误 System.InvalidOperationExce

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

[HttpPost]
public  ActionResult TTS(string text)
{
   SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
   speechSynthesizer.Speak(text);
   return View();
}
但它给出了以下错误

System.InvalidOperationException:'不能执行异步操作
从这个时候开始。异步操作只能在
异步处理程序或模块,或在页面生命周期中的某些事件期间。
如果在执行页面时发生此异常,请确保该页面是
标记
此异常还可能表示有人试图调用“async void”方法,
这在ASP.NET请求处理中通常不受支持。相反
异步方法应该返回一个任务,调用方应该等待它。
我在wpf应用程序中使用了System.Speech类和异步方法

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

  • 怎么做

  • 应该在哪里 安置

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

    我认为您可以尝试使用
    async
    controller操作方法,并与
    Task一起使用

    [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;
    }
    
    查看

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

    类似问题:

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