zoukankan      html  css  js  c++  java
  • 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 = 206;
                    context.Response.AddHeader("status", "206");
                }
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (var reader = new BinaryReader(stream))
                {
                    long fileSize = stream.Length;
    
                    long startPosition = 0;
                    long partialSize = fileSize;
                    if (reqBlockRange != null)
                    {
                //safari startPosition
    = Convert.ToInt64(reqBlockRange[0]); if(reqBlockRange.Length > 1) { long endPosition = fileSize; if (long.TryParse(reqBlockRange[1], out endPosition)) { partialSize = endPosition - startPosition + 1; } }else {
                  // chrome 等 partialSize
    = fileSize - startPosition; } } byte[] buffer = new byte[(int)partialSize]; reader.BaseStream.Seek(startPosition, SeekOrigin.Begin); reader.Read(buffer, 0, (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); } }
  • 相关阅读:
    中介者模式
    Redis安装
    观察者模式
    第三天:创建型模式--建造者模式
    第二天:创建型模式--抽象工厂模式
    第一天:创建型模式--工厂方法模式
    17天17个Python设计模式--目录
    Python模拟登陆新版知乎
    Flask架站基础篇(八)--SQLAlchemy(2)
    Flask架站基础篇(七)--SQLAlchemy(1)
  • 原文地址:https://www.cnblogs.com/kunlunmountain/p/10024537.html
Copyright © 2011-2022 走看看