2015-05-13 51 views
0

我需要將上傳的視頻文件與載波轉換。上傳者:Carrierwave路徑上傳文件中的版本化文件

class MediaItemUploader < CarrierWave::Uploader::Base 
    version :video_for_device, if: :video? do 
    process :encode_video_for_device 
    end 

    storage :file 

    private 

    def video? file 
     if file.path.ends_with?('avi') || ... 
     true 
     else 
     false 
     end 
    end 

    def encode_video_for_device 
     input_file = file.path 
     output_file = # How to get the output file path? 
     system("ffmpeg -i #{input_file} -vcodec libx264 -acodec aac -strict -2 #{output_file}") 
    end 
end 

但是,如何獲得輸出文件路徑並告訴carrierwave附加此文件? 如果我的代碼是output_file,那麼ffmpeg可以正常工作,但carrierwave會將與原始文件一起放入名爲'video_for_device _#{original_filename}'的文件。但我需要處理這個新文件。

回答

0

你必須返回該方法的結尾處​​理的文件,所以這應該這樣做:

def encode_video_for_device 
    input_file = file.path 
    output_file = "/whatever/temp/filename" 
    system("ffmpeg -i #{input_file} -vcodec libx264 -acodec aac -strict -2 #{output_file}") 
    File.new(output_file) 
end 
+0

不行,它不起作用。 Carrierwave創建一個名爲'video_for_device _...'的文件以及原始文件,它是原始文件的副本。 –

0

這裏是一個解決方案:

def encode_video_for_device 
    tmp_path = File.join File.dirname(current_path), "#{SecureRandom.hex}.mp4" 
    system("ffmpeg -i #{current_path} -vcodec libx264 -acodec aac -strict -2 #{tmp_path}") 
    File.rename tmp_path, current_path 
end 

current_path是當前文件的路徑在附着之前必須進行修改。