Question

I created a rails class with a video attachment, and i want to know how to get the length of a video that is uploaded to my application. How can I achieve that ?

Was it helpful?

Solution

Use ffmpeg and the RVideo gem, which is a thin Ruby wrapper around it. There's a lot of forks of the RVideo project, personally I use http://github.com/greatseth/rvideo because it supports capturing frames from video and saving them as images. When it's all set up, you can do this:

# 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

OTHER TIPS

I didn't get Rvideo working on fully, the gem hasn't been updated in four years. However, this works:

  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

I had to do this recently, and this was my approach:

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 is installed by ffmpeg, so if you have that installed you're probably good to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top