How to save audio from using Windows.Media.SpeechSynthesis?

157 views Asked by At

I´m using Windows.Media.SpeechSynthesis for TTS and playing an audio signal works fine in my WPF application. I have wanted to save an audio signal but if I call StorageFolder I get an error: HRESULT: 0x80073D54 - The process has no package identity. How to fix it? The whole code is below. I would also like to know what rights apply to the use of an audio file from Win 10 TTS? I didn't find it anywhere - but I wasn't looking for that much...

private async void Talk(string text)
{
    var stream = await speechSynthesizer.SynthesizeTextToStreamAsync(text);

    StorageFolder localfolder = ApplicationData.Current.LocalFolder;
    StorageFile sampleFile = await localfolder.CreateFileAsync("sample.wav", CreationCollisionOption.ReplaceExisting);
    using (var reader = new DataReader(stream))
    {
        await reader.LoadAsync((uint)stream.Size);
        IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
        await FileIO.WriteBufferAsync(sampleFile, buffer);
    }
}
1

There are 1 answers

0
Jan Nowak On

Finally, I have found a solution, how to save a stream from tts into *.wav or to *.mp3 by Naudio. I don´t know if it is clear but it is functional:

public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
    try
    {
        using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            fs.Write(byteArray, 0, byteArray.Length);
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in process: {0}", ex);
        return false;
    }
}

private async Task SaveAudio(string text)
{
    var stream = await speechSynthesizer.SynthesizeTextToStreamAsync(text);

    using (var reader = new DataReader(stream))
    {
        await reader.LoadAsync((uint)stream.Size);
        IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
        DataReader dataReader = DataReader.FromBuffer(buffer);
        byte[] bytes = new byte[buffer.Length];
        dataReader.ReadBytes(bytes);
        //ByteArrayToFile("sample.wav", bytes);
        ConvertWavStreamToMp3File(bytes, TB_File.Text);
        MessageBox.Show("Audio was saved to file: " + TB_File.Text, "Info");
    }
}

public static void ConvertWavStreamToMp3File(byte[] wavFile, string savetofilename)
{
    using (var retMs = new MemoryStream())
    using (var ms = new MemoryStream(wavFile))
    using (var rdr = new WaveFileReader(ms))

    using (var wtr = new LameMP3FileWriter(savetofilename, rdr.WaveFormat, LAMEPreset.VBR_90))
    {
        rdr.CopyTo(wtr);
    }
}