如何使用paperclip设置taglib-ruby

时间:2016-03-20 18:48:20

标签: ruby-on-rails paperclip taglib-ruby

我有一个轨道模型,通过回形针成功将mp3文件上传到s3,并且还成功获取通过mp3-info提取的元数据。唯一的问题是,我想提取上传的mp3文件的封面艺术,而mp3-info不支持这个。我应该如何在这个模型中实现taglib-ruby来提取封面并在通过回形针保存之前存储它?

    class Track < ActiveRecord::Base
    belongs_to :artist 
    belongs_to :album

    validates :artist_id, presence: true

    has_attached_file :audio,
     storage: :s3, s3_credentials: {access_key_id: ENV["AWS_ACCESS_KEY_ID"],
     secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]}, bucket: 'musicstreamdata'

    validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ]

    validates :audio, presence: true

    before_save :extract_metadata
    serialize :metadata

    # defines audio type

    def audio?
        audio_content_type =~ %r{^audio/(?:mp3|mpeg|mpeg3|mpg|x-mp3|x-mpeg|x-mpeg3|x-mpegaudio|x-mpg)$}
    end

    def display_name
      @display_name ||= if audio? && metadata?
        artist, title = metadata.values_at('artist', 'title')
        title.present? ? [title, artist].compact.join(' - ').force_encoding('UTF-8') : audio_file_name
      else
        audio_file_name
      end
    end


        private

    # Retrieves metadata for MP3s

    def extract_metadata
      return unless audio?
      path = audio.queued_for_write[:original].path
      open_opts = { :encoding => 'utf-8' }
      Mp3Info.open(path, open_opts) do |mp3info|
        self.metadata = mp3info.tag
      end
    end


    # code below not working, need help implementing correctly

    def extract_cover
      # Load an ID3v2 tag from a file
      open_opts = { :encoding => 'utf-8' }
    TagLib::MPEG::File.open(audio.queued_for_write[:original].path, open_opts ) do |file|
      tag = file.id3v2_tag

      # Access all frames
      tag.frame_list.size  #=> 13

      # Track frame
      track = tag.frame_list('TRCK').first
      track.to_s  #=> "7/10"

      # Attached picture frame
      cover = tag.frame_list('APIC').first
      cover.mime_type  #=> "image/jpeg"
      cover.picture  #=> "\xFF\xD8\xFF\xE0\x00\x10JFIF..."
      end 
    end
end

0 个答案:

没有答案