解决IOS通过HTML5播放Video或者Audio直接输出数据的问题

xiaoxiao2021-02-27  305

大家都知道HTML5通过Video或者Audio标签的src属性可以直接播放网络路径的视频或者音频,IOS对于直接读取文件是没问题的,但是如果需要输出数据的方式读取就有问题,是打不开文件的,为了完美支持html5的视频播放,必须支持byte-range请求。因为html5播放视频之前会发送一个只需文件少数字节的请求,确认服务端是否支持byte-range请求,支持才会继续发送请求剩余的文件数据。

下载代码:

private void RangeDownload(string fullpath, HttpContext context) { long size, start, end, length, fp = 0; using (StreamReader reader = new StreamReader(fullpath)) { size = reader.BaseStream.Length; start = 0; end = size - 1; length = size; context.Response.AddHeader("Accept-Ranges", "0-" + size); if (!String.IsNullOrEmpty(context.Request.ServerVariables["HTTP_RANGE"])) { long anotherStart = start; long anotherEnd = end; string[] arr_split = context.Request.ServerVariables["HTTP_RANGE"].Split(new char[] { Convert.ToChar("=") }); string range = arr_split[1]; // Make sure the client hasn't sent us a multibyte range if (range.IndexOf(",") > -1) { context.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + size); throw new HttpException(416, "Requested Range Not Satisfiable"); } if (range.StartsWith("-")) { // The n-number of the last bytes is requested anotherStart = size - Convert.ToInt64(range.Substring(1)); } else { arr_split = range.Split(new char[] { Convert.ToChar("-") }); anotherStart = Convert.ToInt64(arr_split[0]); long temp = 0; anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : size; } anotherEnd = (anotherEnd > end) ? end : anotherEnd; if (anotherStart > anotherEnd || anotherStart > size - 1 || anotherEnd >= size) { context.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + size); throw new HttpException(416, "Requested Range Not Satisfiable"); } start = anotherStart; end = anotherEnd; length = end - start + 1; // Calculate new content length fp = reader.BaseStream.Seek(start, SeekOrigin.Begin); context.Response.StatusCode = 206; } } // Notify the client the byte range we'll be outputting context.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + size); context.Response.AddHeader("Content-Length", length.ToString()); // Start buffered download context.Response.WriteFile(fullpath, fp, length); //context.Response.End(); }

调用:

if (System.IO.File.Exists(fullPath)) { HttpContext context = System.Web.HttpContext.Current; string mimetype = GetContentType(path); if (System.IO.File.Exists(fullPath)) { context.Response.ContentType = mimetype; if (!String.IsNullOrEmpty(context.Request.ServerVariables["HTTP_RANGE"])) { //request for chunk RangeDownload(fullPath, context); } else { //ask for all long fileLength = File.OpenRead(fullPath).Length; context.Response.AddHeader("Content-Length", fileLength.ToString()); context.Response.WriteFile(fullPath); } } else { throw new HttpException(404, "Video Not Found Path:" + fullPath); } }

转载请注明原文地址: https://www.6miu.com/read-3715.html

最新回复(0)