【问题标题】:What is the proper way to serve mp4 files through rails to an Ipad?通过rails向Ipad提供mp4文件的正确方法是什么?
【发布时间】:2013-05-03 06:29:09
【问题描述】:

我们无法使用默认的 rails 3 应用程序提供可在 ipad 上播放的 mp4。在桌面上的 chrome 和其他浏览器中查看路线时,mp4 会正确提供。

这是我们的代码:

file_path = File.join(Rails.root, 'test.mp4')
send_file(file_path, :disposition => "inline", :type => "video/mp4")

我们点击 0.0.0.0:3000/video/test.mp4 来观看视频并在 ipad 上显示无法播放图标。我们已经尝试修改各种标题“Content-Length”、“Content-Range”等,但它们似乎不会影响最终结果。

我们也在一定程度上尝试过使用 send_data

File.open(file_path, "r") do |f|
    send_data f.read, :type => "video/mp4"
end 

在 Ipad 上观看时,可以从公共文件夹中正常播放相同的视频。

通过 rails 将 mp4 文件传送到 Ipad 的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ipad mp4


    【解决方案1】:

    问题似乎是 rails 无法处理 ios 流式传输 mp4 所需的 http-range 请求。

    这是我们的开发解决方案,(使用 Thin 作为我们的服务器):

      if(request.headers["HTTP_RANGE"]) && Rails.env.development?
    
        size = File.size(file_path)
        bytes = Rack::Utils.byte_ranges(request.headers, size)[0]
        offset = bytes.begin
        length = bytes.end - bytes.begin + 1
    
        response.header["Accept-Ranges"]=  "bytes"
        response.header["Content-Range"] = "bytes #{bytes.begin}-#{bytes.end}/#{size}"
        response.header["Content-Length"] = "#{length}"
    
        send_data IO.binread(file_path,length, offset), :type => "video/mp4", :stream => true,  :disposition => 'inline',
                  :file_name => file_name
    
      else
        send_file(file_path, :disposition => 'inline', :stream => true, :file_name => file_name)
      end
    

    最终我们将使用 nginx XSendfile 来为我们的生产环境中的资产提供服务,因为上述解决方案比我们需要的要慢得多。

    【讨论】:

    • 我认为代码中有一个栅栏错误。我相信长度应该是bytes.end - bytes.begin + 1 - 如果字节范围是从字节 10 到 12,那应该是 3 个字节。此外,如果您出于某种原因使用send_data,请务必在响应标头中设置Content-Length
    • 感谢您提供此解决方案!我根据@tovodeverett 评论添加了更正。使用 Sinatra(而不是 Rails)进行开发,我设法使用 sinatra/streaming contrib 复制了 send_data 行为,如下所示:stream {|out| out.write IO.binread(file_path,length, offset); out.flush}
    • 感谢您的解决方案!我们注意到,为了使这种方法在 Chrome 中工作,必须将响应状态显式设置为 206
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2018-11-04
    • 2013-01-17
    • 2022-08-17
    • 1970-01-01
    相关资源
    最近更新 更多