Ruby on rails RubyonRails:作为回形针附件的视频长度

Ruby on rails RubyonRails:作为回形针附件的视频长度,ruby-on-rails,ruby,video,attachment,paperclip,Ruby On Rails,Ruby,Video,Attachment,Paperclip,我创建了一个带有视频附件的rails类,我想知道如何获取上传到我的应用程序的视频长度。如何实现这一点?使用ffmpeg和RVideogem,它是一个很薄的Ruby包装。RVideo项目有很多分支,我个人使用http://github.com/greatseth/rvideo,因为它支持从视频中捕获帧并将其保存为图像。设置完毕后,您可以执行以下操作: # For Paperclip 2 video_attributes = RVideo::Inspector.new(:file => sel

我创建了一个带有视频附件的rails类,我想知道如何获取上传到我的应用程序的视频长度。如何实现这一点?

使用
ffmpeg
RVideo
gem,它是一个很薄的Ruby包装。
RVideo
项目有很多分支,我个人使用
http://github.com/greatseth/rvideo
,因为它支持从视频中捕获帧并将其保存为图像。设置完毕后,您可以执行以下操作:

# For Paperclip 2
video_attributes = RVideo::Inspector.new(:file => self.upload.to_file.path, :ffmpeg_binary => "/usr/local/bin/ffmpeg" )
video_attributes.duration # duration in milliseconds

# For Paperclip 3
video_attributes = RVideo::Inspector.new(:file => self.upload.queued_for_write[:original].path)
video_attributes.duration # duration in milliseconds

我没有让Rvideo完全工作,gem已经四年没有更新了。然而,这是可行的:

  before_post_process :get_video_duration

  def get_video_duration
    result = `ffmpeg -i #{self.video.to_file.path} 2>&1`
    r = result.match("Duration: ([0-9]+):([0-9]+):([0-9]+).([0-9]+)")
    if r
      self.duration = r[1].to_i*3600+r[2].to_i*60+r[3].to_i
    end
  end

我最近不得不这么做,这就是我的方法:

before_post_process do
  file = data.queued_for_write[:original].path
  self.duration = Paperclip.run("ffprobe", '-i %s -show_entries format=duration -v quiet -of csv="p=0"' % file).to_f
end

ffprobe
是由ffmpeg安装的,因此如果您安装了它,您可能就可以开始了。

这是可行的,但是如果您还没有存储,您可能需要为视频使用staged_路径:
ffmpeg-i#{self.video.staged_path}2>&1,这对我很有效