2010-09-10 61 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