我有以下代码下载视频内容:
WebRequest wreq = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse()) using (Stream mystream = wresp.GetResponseStream()) { using (BinaryReader reader = new BinaryReader(mystream)) { int length = Convert.ToInt32(wresp.ContentLength); byte[] buffer = new byte[length]; buffer = reader.ReadBytes(length); Response.Clear(); Response.Buffer = false; Response.ContentType = "video/mp4"; //Response.BinaryWrite(buffer); Response.OutputStream.Write(buffer,buffer.Length); Response.End(); } }
但问题是整个文件在播放之前下载.如何让它流式传输和播放,因为它仍在下载?还是由客户/接收者应用来管理?
解决方法
您正在将整个文件读入单个缓冲区,然后一次发送整个字节数组.
您应该在while循环中读入较小的缓冲区.
例如:
byte[] buffer = new byte[4096]; while(true) { int bytesRead = myStream.Read(buffer,buffer.Length); if (bytesRead == 0) break; Response.OutputStream.Write(buffer,bytesRead); }