我正在尝试使用Microsoft语音对象库将文本转换为C#中的音频。将音频直接保存到wav文件时,我已经成功完成了此操作,但是我的主要目标是将音频保存到字节数组,然后可以在asp.net中写出响应(这样最终用户可以将其下载到他们的机器)。
当我尝试打开写到响应的wav文件时,该文件无法下载,但没有播放任何内容,并显示了Windows Media Player无法打开该文件的错误。
下面的代码显示了我在做什么,哪些没有。
任何人都只是想将字节数组写为wav时,对第二部分中可能缺少的内容有任何想法?
////////////////////////////////////////////////
// THIS WORKS
//SpVoice my_Voice = new SpVoice(); //declaring and initializing SpVoice Class
//SpeechVoiceSpeakFlags my_Spflag = SpeechVoiceSpeakFlags.SVSFlagsAsync; // declaring and initializing Speech Voice Flags
//SpFileStream spFileStream = new SpFileStream(); //declaring and Initializing fileStream obj
//SpeechStreamFileMode spFileMode = SpeechStreamFileMode.SSFMCreateForWrite; //declaring fileStreamMode as to Create or Write
//spFileStream.Open("C:\\temp\\hellosample.wav", spFileMode, false);
//my_Voice.AudioOutputStream = spFileStream;
//my_Voice.Speak("test text to audio in asp.net", my_Spflag);
//my_Voice.WaitUntilDone(-1);
//spFileStream.Close();
////////////////////////////////////////////////
////////////////////////////////////////////////
// THIS DOES NOT WORK
SpVoice my_Voice = new SpVoice(); //declaring and initializing SpVoice Class
SpeechVoiceSpeakFlags my_Spflag = SpeechVoiceSpeakFlags.SVSFlagsAsync; // declaring and initializing Speech Voice Flags
SpMemoryStream spMemStream = new SpMemoryStream();
spMemStream.Format.Type = SpeechAudioFormatType.SAFT11kHz8BitMono;
object buf = new object();
my_Voice.AudioOutputStream = spMemStream;
my_Voice.Speak("test text to audio!", my_Spflag);
my_Voice.WaitUntilDone(-1);
spMemStream.Seek(0, SpeechStreamSeekPositionType.SSSPTRelativeToStart);
buf = spMemStream.GetData();
byte[] byteArray = (byte[])buf;
Response.Clear();
Response.ContentType = "audio/wav";
Response.AppendHeader("Content-Disposition", "attachment; filename=mergedoutput.wav");
Response.BinaryWrite(byteArray);
Response.Flush();
////////////////////////////////////////////////
最佳答案
我建议您在SpeechSynthesizer
程序集中而不是Microsoft Speech Object Library中使用System.Speech
类,因为该程序集包含在.NET库中。
我在下面发布了一个示例,以说明如何使用在ASP.NET MVC上创建的SpeechSynthesizer
类解决问题。希望这能解决您的问题。
public class HomeController : Controller
{
public async Task<ActionResult> Index()
{
Task<FileContentResult> task = Task.Run(() =>
{
using (var synth = new SpeechSynthesizer())
using (var stream = new MemoryStream())
{
synth.SetOutputToWaveStream(stream);
synth.Speak("test text to audio!");
byte[] bytes = stream.GetBuffer();
return File(bytes, "audio/x-wav");
}
});
return await task;
}
}
关于c# - 如何编写wav字节数组以使用Microsoft Speech Object Library进行响应?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22184287/