2

How do I convert a WaveStream to a Byte Array using NAudio?

Hedge
  • 16,142
  • 42
  • 141
  • 246
  • possible duplicate of [How to write NAudio WaveStream to a Memory Stream?](http://stackoverflow.com/questions/11500222/how-to-write-naudio-wavestream-to-a-memory-stream) – Daniel Hilgarth Jan 23 '13 at 14:05

3 Answers3

2
public static class StreamExtension
{
    public static byte[] ToArray(this Stream stream)
    {
        byte[] buffer = new byte[4096];
        int reader = 0;
        MemoryStream memoryStream = new MemoryStream();
        while ((reader = stream.Read(buffer, 0, buffer.Length)) != 0)
            memoryStream.Write(buffer, 0, reader);
        return memoryStream.ToArray();
    }
}
Denis
  • 5,894
  • 3
  • 17
  • 23
  • this is the right approach, but the buffer size should be configurable to be an exact multiple of the block align of the WaveStream. Usually one or two seconds of audio at a time would be a good size to read. – Mark Heath Jan 23 '13 at 17:38
  • visual studio says no need to assign at declaration to `int reader` – Brian Hong Aug 23 '20 at 22:23
1

You can try this vision and should work for you, try it

  MemoryStream memoryStr = new MemoryStream();
            while ((read = stream.Read(buffer, 0, buffer.Length)) != 0)
                memoryStr.Write(buffer, 0, read );
Luis Pedro
  • 21
  • 2
0

You use it like a System.IO.Stream. Use the Read Method. But remember. If you convert the whole stream into ONE Bytearray it could cause and OutOfMemoryException. It depends on how big the stream is. But you could use something like this:

byte[] buffer = new byte[stream.Length];
int read = stream.Read(buffer, 0, buffer.Length);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Florian
  • 5,918
  • 3
  • 47
  • 86