我有以下代码下载视频内容:
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, 0, buffer.Length);
Response.End();
}
}
但问题是整个文件在播放前下载。如何进行流式处理和播放,因为它仍在下载?或者由客户/接收器应用程序来管理?
答案 0 :(得分:22)
您正在将整个文件读入单个缓冲区,然后立即发送整个字节数组。
您应该在while
循环中读入较小的缓冲区。
例如:
byte[] buffer = new byte[4096];
while(true) {
int bytesRead = myStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
Response.OutputStream.Write(buffer, 0, bytesRead);
}
答案 1 :(得分:2)
你看过Smooth Streaming吗?
查看示例代码here
答案 2 :(得分:2)
这对您更有效,特别是如果您需要从服务器上的文件流式传输视频,或者甚至此文件托管在其他服务器上
文件在您的服务器上:
context.Response.BinaryWrite(File.ReadAllBytes(HTTPContext.Current.Server.MapPath(_video.Location)));
外部服务器上的文件:
var wc = new WebClient();
context.Response.BinaryWrite(wc.DownloadData(new Uri("http://mysite/video.mp4")));