I have a problem with streaming video. I developed the server on ASP.NET Web API 2 and implemented 2 methods:
The first method:
if (Request.Headers.Range != null)
{
try
{
var httpResponce = Request.CreateResponse();
httpResponce.Content =
new PushStreamContent((Action<Stream, HttpContent, TransportContext>) WriteContentToStream);
return httpResponce;
}
catch (Exception ex)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
else
{
return new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable);
}
/*method for streaming*/
private async void WriteContentToStream(Stream outputStream, HttpContent content, TransportContext transportContext)
{
string relativeFilePath = "~/App_Data/Videos/4.mp4";
try
{
var filePath = System.Web.Hosting.HostingEnvironment.MapPath(relativeFilePath);
int bufferSize = 1000;
byte[] buffer = new byte[bufferSize];
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
int totalSize = (int)fileStream.Length;
while (totalSize > 0)
{
int count = totalSize > bufferSize ? bufferSize : totalSize;
int sizeOfReadedBuffer = fileStream.Read(buffer, 0, count);
await outputStream.WriteAsync(buffer, 0, sizeOfReadedBuffer);
totalSize -= sizeOfReadedBuffer;
}
}
}
catch (HttpException ex)
{
if (ex.ErrorCode == -2147023667)
{
return;
}
}
finally
{
outputStream.Close();
}
}
2) The second method:
public HttpResponseMessage Test()
{
if (Request.Headers.Range != null)
{
try
{
string relativeFilePath = "~/App_Data/Videos/4.mp4";
var filePath = System.Web.Hosting.HostingEnvironment.MapPath(relativeFilePath);
HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
partialResponse.Headers.AcceptRanges.Add("bytes");
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
partialResponse.Content = new ByteRangeStreamContent(stream, Request.Headers.Range, new MediaTypeHeaderValue("video/mp4"));
return partialResponse;
}
catch (Exception)
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
else
{
return new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable);
}
}
Both of these methods worked on Web-client and Android-client, but iOS-client doesn't show video.
I think, that problem may be with codec of video (but I used codecs, which recommend Apple) or http-headers.