c# – 如何在asp.net中流式传输视频内容?

前端之家收集整理的这篇文章主要介绍了c# – 如何在asp.net中流式传输视频内容?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码下载视频内容
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);
}
原文链接:https://www.f2er.com/csharp/95064.html

猜你在找的C#相关文章