Ok, điều này có lẽ không phải là tối ưu nhưng nó hoạt động khá tốt. Tôi đã kết thúc việc thêm một tệp đính kèm khác vào lớp Sound
của mình cho mp3 và thêm bộ lọc before_validation
để móc vào nó. Ngoài ra, vì tôi đã có một số tệp đính kèm wav hiện có, tôi đã tạo phương thức reconvert_to_mp3
để xử lý việc di chuyển các bản ghi hiện có.
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
Nguồn
2010-09-10 22:10:09
Không nên có 'dst.unlink' ở dưới cùng? Hoặc sẽ xóa tập tin trước khi Paperclip có thể lấy nó? – user1618143
@daniel Cảm ơn vì giải pháp hoạt động tuyệt vời của nó. Nhưng tôi đang đối mặt với một số vấn đề trong chế độ sản xuất. Lỗi như sau: 'Lỗi đọc tiêu đề trong tệp đầu vào mp3 'Bạn có thể giúp tôi với điều này không? Cảm ơn rất nhiều. – Vishal