Dan*_*ore 5 mp3 ruby-on-rails wav paperclip
我有一个Rails应用程序,人们可以使用浏览器声音编辑器创建wav文件并将它们上传到服务器.
我使用Paperclip处理声音文件上传.
我希望能够将wav文件转换为mp3,但保留两个文件.
我已经阅读了Paperclip处理器,但我不知道如何使用它们来获取这两个文件,而不仅仅是转换为mp3.
好吧,这可能不是最佳的,但它的效果非常好.我最后在我的Sound
类中为mp3 添加了另一个附件,并添加了一个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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2564 次 |
最近记录: |