答案是:yes, 您可以使用System.Speech
MVC 中的类。
我想你可以尝试使用async
控制器动作方法及使用SpeechSynthesizer.Speak https://msdn.microsoft.com/en-us/library/system.speech.synthesis.speechsynthesizer.speak(v=vs.110).aspx with 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;
}
但是,如上面的示例所示,生成的声音在服务器上播放,因为上面的代码在服务器端而不是客户端运行。要启用在客户端播放,您可以使用SetOutputToWaveFile https://msdn.microsoft.com/en-us/library/ms586883(v=vs.110).aspx方法及用途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;
}
View
<audio autoplay="autoplay" src="@Url.Content("~/path/to/file/" + ViewBag.FileName)">
</audio>
或者您可以将操作类型更改为FileContentResult
并使用MemoryStream
with SetOutputToWaveStream https://msdn.microsoft.com/en-us/library/system.speech.synthesis.speechsynthesizer.setoutputtowavestream(v=vs.110).aspx让用户自己播放音频文件:
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");
}
}
});
参考:
在 ASP.NET MVC 中使用异步方法 https://learn.microsoft.com/en-us/aspnet/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4
类似问题:
mvc中如何使用语音 https://forums.asp.net/t/2003629.aspx?How%20to%20use%20speech%20in%20mvc
System.Speech.Synthesis 在 2012 R2 上因 CPU 高而挂起 https://stackoverflow.com/questions/32236923/system-speech-synthesis-hangs-with-high-cpu-on-2012-r2