2010-09-10 63 views
5

我有一個Rails應用程序,人們可以使用瀏覽器聲音編輯器來創建wav文件並將它們上傳到服務器。用Paperclip上傳WAV文件並存儲.wav和.mp3版本

我使用Paperclip來處理聲音文件上傳。

我想能夠將wav文件轉換爲mp3,但保留這兩個文件。

我已閱讀有關回形針處理器,但我不知道如何使用它們來獲取這兩個文件,而不是隻轉換爲MP3。

回答

7

好吧,這可能不是最佳的,但它工作得很好。我最後爲我的Sound類添加了另一個附件,並添加了一個before_validation過濾器來掛接它。另外,由於我有一些現有的wav附件,我創建了一個reconvert_to_mp3方法來處理現有記錄的遷移。

has_attached_file :mp3, 
    :storage => :s3, 
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml", 
    :path => "sounds/:id/:style.:extension" 

before_validation :convert_to_mp3 

def reconvert_to_mp3 
    wavfile = Tempfile.new(".wav") 
    wavfile.binmode 

    open(wav.url) do |f| 
    wavfile << f.read 
    end 

    wavfile.close 

    convert_tempfile(wavfile) 
end 

def convert_to_mp3 
    tempfile = wav.queued_for_write[:original] 

    unless tempfile.nil? 
    convert_tempfile(tempfile) 
    end 
end 

def convert_tempfile(tempfile) 
    dst = Tempfile.new(".mp3") 

    cmd_args = [File.expand_path(tempfile.path), File.expand_path(dst.path)] 
    system("lame", *cmd_args) 

    dst.binmode 
    io = StringIO.new(dst.read) 
    dst.close 

    io.original_filename = "sound.mp3" 
    io.content_type = "audio/mpeg" 

    self.mp3 = io 
end 
+0

底部不應該有'dst.unlink'嗎?或者在Paperclip抓取它之前刪除文件? – user1618143 2013-12-19 16:45:05

+0

@丹尼爾感謝您的解決方案,它的工作很棒。但是我在生產模式中遇到了一些問題。錯誤如下:'讀取mp3輸入文件中的標題錯誤'你能幫我解決這個問題嗎?非常感謝。 – Vishal 2017-08-23 09:25:59