我正在尝试使用 WebAPI 设置一个简单的 Web 服务。这是我的代码:
public class SpeakController : ApiController
{
//
// api/speak
public HttpResponseMessage Get(String textToConvert, String outputFile, string gender, string age = "Adult")
{
VoiceGender voiceGender = (VoiceGender)Enum.Parse(typeof(VoiceGender), gender);
VoiceAge voiceAge = (VoiceAge)Enum.Parse(typeof(VoiceAge), age);
using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
{
synthesizer.SelectVoiceByHints(voiceGender, voiceAge);
synthesizer.SetOutputToWaveFile(outputFile, new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
synthesizer.Speak(textToConvert);
}
return Request.CreateResponse(HttpStatusCode.OK, new Response { HttpStatusCode = (int)HttpStatusCode.OK, Message = "Payload Accepted." });
}
}
代码相当简单,而且还没有准备好生产。但是在我的测试中,我注意到对控制器的任何请求都会发生以下情况:
- WAV 文件生成成功
- 在调试期间,我可以看到控件点击返回并退出该方法
- 但是,我的浏览器一直在旋转,我从来没有从服务器得到响应
我对 Postman(Chrome 的 REST 客户端)进行了同样的尝试,得到了相同的结果。虽然我确实希望这是一个阻塞调用,但为了尝试其他我修改过的东西synthesizer.Speak
并synthesizer.SpeakAsync
遇到同样的问题。
但是,当我如下所示分别测试代码片段时,代码按预期工作。
测试带有语音部分的 WebAPI 调用已注释掉:
public class SpeakController : ApiController
{
//
// api/speak
public HttpResponseMessage Get(String textToConvert, String outputFile, string gender, string age = "Adult")
{
VoiceGender voiceGender = (VoiceGender)Enum.Parse(typeof(VoiceGender), gender);
VoiceAge voiceAge = (VoiceAge)Enum.Parse(typeof(VoiceAge), age);
//using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
//{
// synthesizer.SelectVoiceByHints(voiceGender, voiceAge);
// synthesizer.SetOutputToWaveFile(outputFile, new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
// synthesizer.Speak(textToConvert);
//}
return Request.CreateResponse(HttpStatusCode.OK, new Response { HttpStatusCode = (int)HttpStatusCode.OK, Message = "Payload Accepted." });
}
}
在控制台应用程序中单独测试语音:
static string usageInfo = "Invalid or no input arguments!"
+ "\n\nUsage: initiatives \"text to speak\" c:\\path\\to\\generate.wav gender"
+ "\nGender:\n\tMale or \n\tFemale"
+ "\n";
static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine(usageInfo);
}
else
{
ConvertStringToSpeechWav(args[0], args[1], (VoiceGender)Enum.Parse(typeof(VoiceGender), args[2]));
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
static void ConvertStringToSpeechWav(String textToConvert, String pathToCreateWavFile, VoiceGender gender, VoiceAge age = VoiceAge.Adult)
{
using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
{
synthesizer.SelectVoiceByHints(gender, age);
synthesizer.SetOutputToWaveFile(pathToCreateWavFile, new SpeechAudioFormatInfo(8000, AudioBitsPerSample.Sixteen, AudioChannel.Mono));
synthesizer.Speak(textToConvert);
}
}
WebAPI 和 SpeechSynthesis 似乎不能很好地配合使用。任何帮助弄清楚这一点将不胜感激。
谢谢!