Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if a file is video in Ruby

Tags:

ruby

I am using ruby-2.1 and I want to check if a file is of type video. I want a solution for common for all operating systems.

So I tried the File Object. It has a fnmatch method which only tests for extensions using regex such as *.mp4 or *.avi and so on. But this seems very inefficient.

# Get all files of directory
all_files = Dir.entries(Dir.pwd).select { |x| !File.directory? x}

mp4_f = '*.mp4'
avi_f = '*.avi'
mkv_f = '*.mkv'
flv_f = '*.flv'

# Loop through each file
all_files.each do |file|
    puts File.fnmatch(mp4_f, file) || File.fnmatch(avi_f, file) || File.fnmatch(mkv_f, file) || File.fnmatch(flv_f, file)
end

But this code seems very bad for multitudes of video types. So any solutions, would be appreciated including any gem support. Thanks.

like image 705
Y M Avatar asked Oct 25 '14 07:10

Y M


3 Answers

You have to use something like ffmpeg and parse its output:

`ffmpeg -i somefile.doc`
#=> ....
#=> Invalid data found when processing input

`ffmpeg -i somefile.mp4`
#=> ...
#=> Duration: 00:00:29.84, start: 0.547944, bitrate: 390 kb/s
#=> ...
like image 195
fl00r Avatar answered Nov 04 '22 02:11

fl00r


Use Globbing

One cross-platform way to do this without external dependencies like libmagic is to use Dir#glob to match filename extensions. For example:

extensions  = %w[avi flv mkv mov mp4]
video_files = extensions.flat_map { |ext| Dir.glob "*#{ext}" }

You can then pass the video_files Array around as needed within your program.

like image 2
Todd A. Jacobs Avatar answered Nov 04 '22 02:11

Todd A. Jacobs


You could do something like this without using the ffmpeg library,

vid_formats = %w[.avi .flv .mkv .mov .mp4] #add more extensions if anything is left
all_files.each do |file|
   puts vid_formats.include? File.extname(file)
end

Of course you have to maintain an array for the extension but this looks better in terms of code readability. Hope that helps

like image 2
Pramod Solanky Avatar answered Nov 04 '22 01:11

Pramod Solanky