这是我上传后将视频转换为 MP4 的解决方案。也许不是最干净的,但它有效。我使用 Delayed::Job 来异步处理调用。
def process_video!
if video.attached? && video.blob.content_type != 'video/mp4'
orig_video_tmpfile = "#{Rails.root}/tmp/#{video.blob.key}_#{video.blob.filename.to_s}"
mp4_video_tmpfile = "#{Rails.root}/tmp/#{video.blob.key}_#{video.blob.filename.base}.mp4"
File.open(orig_video_tmpfile, 'wb') do |f|
f.write(video.download)
end
system('ffmpeg', '-i', orig_video_tmpfile, mp4_video_tmpfile)
self.video.attach(
io: File.open(mp4_video_tmpfile),
filename: "#{video.blob.filename.base}.mp4",
content_type: 'video/mp4'
)
File.delete(orig_video_tmpfile)
File.delete(mp4_video_tmpfile)
end
end
handle_asynchronously :process_video!
after_commit :process_video!