How to stream video content in asp.net?
31,987
Solution 1
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:
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);
}
Solution 2
Have you looked at Smooth Streaming?
Look at sample code here
Solution 3
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:
context.Response.BinaryWrite(File.ReadAllBytes(HTTPContext.Current.Server.MapPath(_video.Location)));
File on external server:
var wc = new WebClient();
context.Response.BinaryWrite(wc.DownloadData(new Uri("http://mysite/video.mp4")));
Author by
Kon
.NET Developer 892zJlw0gCrnyXA8 http://weblogs.asp.net/kon
Updated on February 20, 2020Comments
-
Kon about 4 years
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?