Safari 不能播放Video ,Chrome等可以 问题解决。

1  原因分析

https://www.zhihu.com/question/41818719

2 代码实现

1 注意点: 请求时 : header中 range 请求多少长度 代码要返回相应的长度  比如Byte 0-1

  /// <summary>
/// 返回mp4 兼容苹果
/// </summary>
/// <param name="context"></param>
/// <param name="filePath"></param>
private void CreateVideoResponse(HttpContext context, string filePath)
{
var reqRange = context.Request.Headers["Range"];
string[] reqBlockRange = null;
if (!string.IsNullOrEmpty(reqRange))
{
reqBlockRange = reqRange.Replace("bytes=", "").Split(new[] { "-"},StringSplitOptions.RemoveEmptyEntries);
context.Response.StatusCode = ;
context.Response.AddHeader("status", "");
}
using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new BinaryReader(stream))
{
long fileSize = stream.Length; long startPosition = ;
long partialSize = fileSize;
if (reqBlockRange != null)
{
            //safari
startPosition = Convert.ToInt64(reqBlockRange[]);
if(reqBlockRange.Length > )
{
long endPosition = fileSize;
if (long.TryParse(reqBlockRange[], out endPosition))
{
partialSize = endPosition - startPosition + ;
}
}else
{
              // chrome 等
partialSize = fileSize - startPosition;
}
} byte[] buffer = new byte[(int)partialSize];
reader.BaseStream.Seek(startPosition, SeekOrigin.Begin);
reader.Read(buffer, , (int)partialSize); context.Response.AddHeader("accept-ranges", "bytes");
context.Response.AddHeader("access-control-allow-methods", "HEAD, GET, OPTIONS");
context.Response.AddHeader("cache-control", "public, max-age=30726563");
context.Response.ContentType = "video/mp4";
context.Response.Cache.SetLastModified(DateTime.Now);
context.Response.AddHeader("Connection", "keep-alive");
context.Response.AddHeader("content-range", $"bytes {startPosition}-{startPosition + partialSize-1 }/{fileSize}");
context.Response.AddHeader("Content-Length", $"{partialSize}");
context.Response.BinaryWrite(buffer);
} }
上一篇:css实现等高布局 两栏自适应布局 三栏自适应布局


下一篇:Spring Boot设置上传文件大小