1

我有一个轨道模型,它通过回形针成功地将 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
4

0 回答 0