我正在开发UWP TTS(文本到语音)应用程序,但在将语音保存到文件(最好是Mp3格式)时遇到了麻烦。有谁知道如何做到这一点?在WPF中,我使用了NAUDIO和NAUDIO.LAME,但是不幸的是,这似乎不支持UWP。我认为我必须使用Windows.Media.Transcoding API,但是我没有找到任何执行此操作的示例。我在MSDN上的一篇文章中找到了下面的代码,但这是不正确的。
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
try
{
SpeechSynthesisStream stream = await WCSVariables.Synthesizer.SynthesizeTextToStreamAsync(rtbText.Text);
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(file, buffer);
}
}
catch (Exception ex)
{
MessageDialog msgdlg = new MessageDialog(ex.Message);
msgdlg.ShowAsync();
}
**********更新**********
添加了TXT和MP3的功能和文件类型关联之后,我能够将TXT文件保存在任何文件夹中,但是MP3文件的格式不正确。文件已创建但不播放音频。
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Mp3 Audio File", new List<string>() { ".mp3" });
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "New Document";
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
try
{
if (file.FileType == ".txt")
{
await FileIO.WriteTextAsync(file, rtbText.Text);
}
else
{
string path = file.Path.Remove(file.Path.IndexOf(file.Name), file.Name.Length);
StorageFolder mp3Folder = await StorageFolder.GetFolderFromPathAsync(path);
StorageFile mp3File = await mp3Folder.CreateFileAsync(file.Name, CreationCollisionOption.ReplaceExisting);
SpeechSynthesisStream stream = await WCSVariables.Synthesizer.SynthesizeTextToStreamAsync(rtbText.Text);
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(mp3File, buffer);
}
}
}
catch (Exception ex)
{
MessageDialog msgdlg = new MessageDialog(ex.Message);
msgdlg.ShowAsync();
}
}
您可以首先创建一个.mp3文件,然后从基本文本字符串生成语音音频流。之后,将流写入文件。
StorageFolder folder = KnownFolders.VideosLibrary;
StorageFile file = await folder.CreateFileAsync("MyVideo.mp3",CreationCollisionOption.ReplaceExisting);
if (file != null)
{
try
{
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello World");
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
await FileIO.WriteBufferAsync(file, buffer);
}
}
catch {}
}