Ruby on Rails: Lunghezza del video come allegato Paperclip
-
16-09-2019 - |
Domanda
Ho creato una classe rotaie con un allegato video, e voglio sapere come ottenere la lunghezza di un video che è caricato alla mia richiesta. Come posso ottenere questo?
Soluzione
Usa ffmpeg
e la gemma RVideo
, che è un sottile involucro di Ruby intorno ad esso. C'è un sacco di forcelle del progetto RVideo
, personalmente utilizzo http://github.com/greatseth/rvideo
perché supporta la cattura fotogrammi dal video e salvarli come immagini. Quando è tutto pronto, si può fare questo:
# 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
Altri suggerimenti
non ho avuto Rvideo lavorare sul pieno, la gemma non è stato aggiornato in quattro anni. Tuttavia, questo funziona:
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
Ho dovuto fare questo di recente, e questo era il mio approccio:
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
è installato per ffmpeg, quindi se avete installato che probabilmente siete a posto.