I was trying to create a toast notification with text-to-speech as the audio notification. When user type a description like "Let's eat" and save the toast, when the time is come the toast will say "Let's eat". It like an ringtone for toast.
I got the answer from Social MSDN how to create an toast notification from text-to-speech, but at my program it always turn to exception.
This is the code for creating text-to-speech toast notification:
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.
This audio later will be use as a custom audio for toast.
I've tested your code in my side. I got the exception "the stream doesn't support write", so the question was very obvious. In your code, you just open stream for read
file.OpenStreamForReadAsync()You should usefile.OpenStreamForWriteAsync()Then it will work.