如何在 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, 0, buffer.Length);
Response.End();
}
}
但问题是整个文件在播放之前下载。如何在仍在下载时使其流式传输和播放?或者这取决于客户端/接收方应用程序来管理?
I have the following code which downloads video content:
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();
}
}
But the problem is that the whole file downloads before being played. How can I make it stream and play as it's still downloading? Or is this up to the client/receiver application to manage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将整个文件读入单个缓冲区,然后立即发送整个字节数组。
您应该在
while
循环中读入较小的缓冲区。例如:
You're reading the entire file into a single buffer, then sending the entire byte array at once.
You should read into a smaller buffer in a
while
loop.For example:
这对您来说更有效,特别是如果您需要从服务器上的文件流式传输视频,或者甚至该文件托管在另一台服务器
上 文件在您的服务器上:
文件在外部服务器上:
This is more efficient for you especially if you need to stream a video from a file on your server or even this file is hosted at another server
File On your server:
File on external server:
您是否看过平滑流媒体?
查看示例代码此处< /a>
Have you looked at Smooth Streaming?
Look at sample code here