I tried to use the System.Speech class to generate speech in ASP.NET mvc application.
[HttpPost]
public ActionResult TTS(string text)
{
SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
speechSynthesizer.Speak(text);
return View();
}
But it gives the following error.
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.
I used the System.Speech class and async methods in wpf applications.
Can the System.Speech class be used in a ASP.NET mvc application?
How to do it?
- Where should be the
<%@ Page Async="true" %>be placed?
The answer is: yes, you can use
System.Speechclass in MVC.I think you can try using
asynccontroller action method and useSpeechSynthesizer.SpeakwithTask.Runmethod like this:However, as in example above the generated sound plays on server, because the code above runs server-side instead of client-side. To enable playing on client-side, you can use
SetOutputToWaveFilemethod and useaudiotag to play audio content when returning view page shown in example below (assumed you're using HTML 5 in CSHTML view):Controller
View
Or you can change action type to
FileContentResultand useMemoryStreamwithSetOutputToWaveStreamto let user play audio file himself:Reference:
Using Asynchronous Methods in ASP.NET MVC
Similar issues:
How to use speech in mvc
System.Speech.Synthesis hangs with high CPU on 2012 R2