Reputation: 79
I have a track model that is successfully uploading mp3 files to s3 via paperclip and that also successfully gets it metadata extracted via mp3-info. The only issue is, I want to extract cover art for the mp3 files uploaded as well and mp3-info does not support this. How should I implement taglib-ruby in this model to extract cover art and store it before save via paperclip?
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
Upvotes: 1
Views: 87