asp.net-mvc-3 - MVC3 操作中的 HTML5 视频无法正常工作

标签 asp.net-mvc-3 html5-video mediaelement.js http-streaming video.js

我正在从 MVC3 站点提供视频, Controller 操作返回返回 FilePathResult 的视频,当尝试在浏览器中播放时,我看到了一些令人沮丧的问题,无论我使用 video.js或 mediaelement.js。

  • Chrome 不允许您使用进度条更改位置,也不允许您在视频播放完毕后重播
  • IE9看起来还不错
  • Firefox 无法正确显示已用时间/剩余时间

但是,如果我只提供托管文件的相对路径,则一切正常。 这些视频只需要对属于特定角色的用户开放,因此这并不是一个真正的选择。

行动:

    [Authorize]
    public ActionResult Video(string fileName)
    {
        var pathBase = Server.MapPath("~/Downloads/Videos/");
        var filePath = pathBase + fileName;
        var contentType = ContentType(fileName);
        return new FilePathResult(filePath, contentType) { FileDownloadName = fileName };
    }

Razor :

   <!-- @t = the video entity -->
   <video width="640" height="360" id="@t.Id" poster="@Url.Action("Video", "Download", new { fileName = @t.Poster })" controls="controls" preload="none">
        <!-- MP4 source must come first for iOS -->
        <source src="@Url.Action("Video", "Download", new { fileName = @t.Mp4 })" type='video/mp4' />
        <!-- WebM for Firefox 4 and Opera -->
        <source src="@Url.Action("Video", "Download", new { fileName = @t.WebM })" type='video/webm' />
        <!-- OGG for Firefox 3 -->
        <source src="@Url.Action("Video", "Download", new { fileName = @t.Ogv })" type='video/ogg' />
        <!-- Fallback flash player for no-HTML5 browsers with JavaScript turned off -->
        <object width="640" height="360" type="application/x-shockwave-flash" data="@Url.Content("~/Content/flashmediaelement.swf")">       
            <param name="movie" value="@Url.Content("~/Content/flashmediaelement.swf")" /> 
            <param name="flashvars" value="controls=true&<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="572738242332256a1702253b791634233e3839" rel="noreferrer noopener nofollow">[email protected]</a>("Video", "Download", new { fileName = @t.Poster })&<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c2cdc8c199e4f1d6c88ae5c7d0cdcbca" rel="noreferrer noopener nofollow">[email protected]</a>("Video", "Download", new { fileName = @t.Mp4 })" />         
            <!-- Image fall back for non-HTML5 browser with JavaScript turned off and no Flash player installed -->
            <img src="@Url.Action("Video", "Download", new { fileName = @t.Poster })" width="640" height="360" alt="@t.Title" 
                title="No video playback capabilities" />
        </object>   
    </video>

最佳答案

我最终编写了一个 HTTP 处理程序来处理这些扩展,尽管 Chrome 的问题似乎与我的处理程序不支持范围请求有关。

我使用以下博客文章来帮助我:http://blogs.visigo.com/chriscoulson/easy-handling-of-http-range-requests-in-asp-net/ 。解决方案(我修改为包括内容类型以及一些基本的安全性)如下:

    public void ProcessRequest(HttpContext context)
    {
        if (!context.Request.RequestContext.HttpContext.User.Identity.IsAuthenticated)
            context.Response.Redirect("~");
        var path =
            context.Request.RequestContext.HttpContext.Server.MapPath(
                context.Request.AppRelativeCurrentExecutionFilePath);
        long size, start, end, length, fp = 0;
        using (StreamReader reader = new StreamReader(path))
        {

            size = reader.BaseStream.Length;
            start = 0;
            end = size - 1;
            length = size;
            // Now that we've gotten so far without errors we send the accept range header
            /* At the moment we only support single ranges.
             * Multiple ranges requires some more work to ensure it works correctly
             * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2
             *
             * Multirange support annouces itself with:
             * header('Accept-Ranges: bytes');
             *
             * Multirange content must be sent with multipart/byteranges mediatype,
             * (mediatype = mimetype)
             * as well as a boundry header to indicate the various chunks of data.
             */
            context.Response.AddHeader("Accept-Ranges", "0-" + size);
            context.Response.ContentType = "video/mp4";
            // header('Accept-Ranges: bytes');
            // multipart/byteranges
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2

            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)
                {
                    // (?) Shoud this be issued here, or should the first
                    // range be used? Or should the header be ignored and
                    // we output the whole content?
                    context.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + size);
                    throw new HttpException(416, "Requested Range Not Satisfiable");

                }

                // If the range starts with an '-' we start from the beginning
                // If not, we forward the file pointer
                // And make sure to get the end byte if spesified
                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;
                }
                /* Check the range and make sure it's treated according to the specs.
                 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
                 */
                // End bytes can not be larger than $end.
                anotherEnd = (anotherEnd > end) ? end : anotherEnd;
                // Validate the requested range and return an error if it's not correct.
                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(path, fp, length);
        context.Response.Flush();
    }

关于asp.net-mvc-3 - MVC3 操作中的 HTML5 视频无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11837681/

相关文章:

c# - MVC Razor View /布局的执行顺序是什么

c# - Entity Framework - 如何获取列?

javascript - 2020 : iOS Safari Video Autoplay Options?

jquery - VideoJS : . flv 无法在 IE 中播放

javascript - MEJS(Media Element JS)有播放功能吗?

javascript - 如何停止所有当前正在播放的 MediaElement 播放器?

javascript - MediaElement.js 中的 Cortado Ogg-player - 几乎可以正常工作

c# - 无法更新外键引用(导航属性)

asp.net-mvc-3 - 将错误消息从 Controller 发送到 ASP.net MVC3 中的 View

ios - 如何在 iOS 应用程序内联播放视频?