简体   繁体   English

将音频从文件写入内存流

[英]write audio to memorystream from file

I'm trying to send this file to the outputstream but cannot figure out why it spits out basically an empty mp3 file. 我正在尝试将此文件发送到outputstream,但无法弄清楚为什么它会吐出一个空的mp3文件。 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();

                }

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. 但是,您不应该假设Read的单个调用实际上会读取所有内容。 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. 目前尚不清楚您使用的是哪个.NET版本,但如果使用的是.NET 4或更高版本,则可以使用Stream.CopyTo使其更简单。

It's also unclear why you're using a MemoryStream at all. 不清楚为什么要使用MemoryStream 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: 或者,如果您使用的是.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 .) (这几乎等同于CopyTo 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM