加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用Paperclip上传WAV文件并存储.wav和.mp3版

发布时间:2020-12-17 03:26:31 所属栏目:百科 来源:网络整理
导读:我有一个Rails应用程序,人们可以使用浏览器声音编辑器创建wav文件并将它们上传到服务器. 我使用Paperclip处理声音文件上传. 我希望能够将wav文件转换为mp3,但保留两个文件. 我已经阅读了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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读