无法在 UWP 上从文本到语音音频创建 URI 文件

Cannot create an URI file from text-to-speech audio on UWP

我试图创建一个将文本转语音作为音频通知的 toast 通知。当用户键入 "Let's eat" 之类的描述并保存 toast 时,时间到了 toast 会说 "Let's eat"。它就像烤面包的铃声。

我从 Social MSDN 那里得到了如何从文本到语音创建吐司通知的答案,但在我的程序中它总是变成异常。

这是创建文本到语音 toast 通知的代码:

 private static async Task<Uri> AudioforToast(string text)
    {
        var voices = SpeechSynthesizer.AllVoices;
        using (var synthesizer = new SpeechSynthesizer())
        {
            if (!String.IsNullOrEmpty(text))
            {
                try
                {
                    synthesizer.Voice = voices.First(gender => gender.Gender == VoiceGender.Female);

                    // Create a stream from the text.
                    SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(text);

                    // And now write that to a file
                    var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("ToastAudio", CreationCollisionOption.ReplaceExisting);
                    using (var fileStream = await file.OpenStreamForReadAsync())
                    {
                        await synthesisStream.AsStream().CopyToAsync(fileStream);
                    }

                    // And then return the file path
                    return new Uri("ms-appdata:///temp/ToastAudio");
                }

                catch (Exception)
                {
                    // If the text is unable to be synthesized, throw an error message to the user.            
                    var messageDialog = new Windows.UI.Popups.MessageDialog("Unable to synthesize text. Toast Audio is default");
                    await messageDialog.ShowAsync();
                }
            }
        }

        // If the text is unable to be synthesized, don't return a custom sound
        return null;
    }

当我尝试调试它时,代码无法将文本转语音结果保存到文件中。

此音频稍后将用作吐司的自定义音频。

When I tried to debug it, the code cannot save the text-to-speech result into file.

我已经在我这边测试了你的代码。我得到了异常"the stream doesn't support write",所以问题很明显。在您的代码中,您只需打开流进行读取 file.OpenStreamForReadAsync() 您应该使用 file.OpenStreamForWriteAsync() 然后它将起作用。