Getting video metadata in ruby script using ffmpeg

2019-05-13 21:32发布

问题:

I want to get metadata of videos referenced by a URL using Ruby. At this point, I found many related posts, but could not find out how to solve my problem.

I tried to use RVideo, but when I do:

file = RVideo::Inspector.new(:file => 'http://www.agreatsite.com/avideo.mp4')

It throws

'ArgumentError: File not found (http://www.agreatsite.com/avideo.mp4)...

So I can't get the information using RVideo (but it works well when I have the file hosted on my local computer).

I then tried to use ffprobe, but I don't know how to read the output. So far, I have the following method, which "shows" the information I want when I run it in the console, but it actually returns "true" and I can't find out how to capture the output I need...

  def media_info
    source = self
    command = <<-end_command
      ffprobe -v quiet -print_format json -show_format -show_streams  #{source}
    end_command
    command.gsub!(/\s+/, " ")
    system(command)
  end

Would love some help, to make this work with either ffprobe or RVideo!

UPDATE: I found a way to get what I needed. Not sure this is the best way to do it:

def get_media_duration

source = self.media[0][:url]    

command = <<-end_command
  ffprobe -v quiet  -show_streams  #{source}
end_command
command.gsub!(/\s+/, " ")

duration = ""
IO.popen(command) { |io| while (line = io.gets) do
                        puts "++ "+line.inspect
                        duration = line.split("duration=")[1].gsub("\n", "") if line.split("duration=").length > 1
                      end
                  }
duration   

end

I guess I could make it work that way, but doesn't seem very elegant to me. Better suggestions would be greatly appreciated!

回答1:

Check streamio-ffmpeg, If you are still looking for a solution. Also ffprobe supports json format now: ffprobe -print_format json -show_streams #{input_file}