Upload a WAV file with Paperclip and store both .wav and .mp3 versions
I have a Rails application where people can use an in browser sound editor to create wav files and upload them t开发者_运维技巧o the server.
I use Paperclip for handling the sound file upload.
I would like to be able to convert the wav file to an mp3, but keep both files.
I have read about Paperclip processors, but I'm not sure how to use them to get both files instead of just converting to mp3 only.
Ok, this probably isn't optimal but it works pretty well. I ended up adding another attachment to my Sound
class for the mp3, and added a before_validation
filter to hook into it. In addition, since I had some existing wav attachments, I created a reconvert_to_mp3
method to handle the migrating of the existing records.
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
精彩评论