write audio to memorystream from file

2019-06-09 06:58发布

问题:

I'm trying to send this file to the outputstream but cannot figure out why it spits out basically an empty mp3 file. As you can see I would get an exception closing the stream prematurely so I have commented out for now. Any pointers appreciated.

using (FileStream mp3file = File.OpenRead(newFile))
                {
                    context.Response.AddHeader("content-transfer-encoding", "binary");
                    context.Response.ContentType = "audio/mpeg";
                    MemoryStream memStream = new MemoryStream();
                    byte[] bytes = new byte[mp3file.Length];
                    memStream.SetLength(mp3file.Length);
                    mp3file.Read(memStream.GetBuffer(), 0, (int)mp3file.Length);
                    memStream.Write(bytes, 0, (int)mp3file.Length);
                    //mp3file.Close();
                    memStream.WriteTo(context.Response.OutputStream);
                    //memStream.Close();

                }

回答1:

This part is the problem:

 byte[] bytes = new byte[mp3file.Length];
 ...
 // Here you're reading into the memory stream buffer...
 mp3file.Read(memStream.GetBuffer(), 0, (int)mp3file.Length);
 // And here you're overwriting it with the byte array full of zeroes!
 memStream.Write(bytes, 0, (int)mp3file.Length);

You shouldn't assuming that a single call to Read will actually read everything anyway though. It's not clear which version of .NET you're using, but if you're using .NET 4 or higher, you can use Stream.CopyTo to make it simpler.

It's also unclear why you're using a MemoryStream at all. Why don't you just copy straight to the output stream?

mp3File.CopyTo(context.Response.OutputStream);

Or if you're using an older version of .NET:

byte[] buffer = new byte[16 * 1024]; // For exmaple...
int bytesRead;
while ((bytesRead = mp3File.Read(buffer, 0, buffer.Length)) > 0)
{
    context.Response.OutputStream.Write(buffer, 0, bytesRead);
}

(This is pretty much the equivalent of CopyTo.)