save stream to file in c# and winrt

2019-01-29 01:14发布

问题:

I have in c# and winrt:

var stream = await speech.GetSpeakStreamAsync(SpeechText.Text, language);

stream is a Windows.Storage.Streams.IRandomAccessStream

So I am completly new to c# and winrt. How i save this stream containg a wav-file to a file? Thanks in advance, Basilius

回答1:

The IRandomAccessStream has a method called GetInputStreamAt http://msdn.microsoft.com/en-US/library/windows/apps/windows.storage.streams.irandomaccessstream

IInputStream inputStream = stream.GetInputStreamAt(0);

This gets you an IInputStream.

The IInputStream interface defines just one method, ReadAsync, which lets you read bytes into an IBuffer object. Windows.Storage.Stream also includes a DataReader class that you create based on an IInputStream object and then read numerous .NET objects from the stream as well as arrays of bytes. http://www.charlespetzold.com/blog/2011/11/080203.html , http://msdn.microsoft.com/library/windows/apps/BR208119

using (var stream = new InMemoryRandomAccessStream())
{
    // for example, render pdf page
    var pdfPage = document.GetPage((uint)i);
    await pdfPage.RenderToStreamAsync(stream);

    // then, write page to file
    using (var reader = new DataReader(stream))
    {
        await reader.LoadAsync((uint)stream.Size);
        var buffer = new byte[(int)stream.Size];
        reader.ReadBytes(buffer);
        await Windows.Storage.FileIO.WriteBytesAsync(file, buffer);
    }
}

now you have a buffer containing all the read bytes.

you can now save this buffer to a file http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html

var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("MyWav.wav", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteBytesAsync(file, buffer);


回答2:

I can't add the code to the comment, so here is the code in vb.net: Dim gesprochenesWort As Windows.Storage.Streams.IRandomAccessStream gesprochenesWort = Await Sprich.GetSpeakStreamAsync("Das ist ein Beispieltext", "de")

    Dim Eingabestream As Windows.Storage.Streams.IInputStream = gesprochenesWort.GetInputStreamAt(0)

    Dim Datenleser As New Windows.Storage.Streams.DataReader(Eingabestream)
    Await Datenleser.LoadAsync(CUInt(gesprochenesWort.Size))

    'Dim Dateipuffer As Byte() = New Byte(CInt(gesprochenesWort.Size) - 1) {}
    Dim Dateipuffer(gesprochenesWort.Size - 1) As Byte

    Datenleser.ReadBytes(Dateipuffer)

    Dim Dateiname As String = "MybestWav.wav"

    Dim Datei = Await Windows.Storage.KnownFolders.MusicLibrary.CreateFileAsync(Dateiname, Windows.Storage.CreationCollisionOption.ReplaceExisting)

    Await Windows.Storage.FileIO.WriteBytesAsync(Datei, Dateipuffer)

;Many thanks to you.

Best regards, Basilius