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.
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
#=> ...
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With