我是一个rails newb,尽管我已经检查了有关使用mp3info进行元数据提取的paperclip文档,但我无法在当前的应用程序中使用它。我正在尝试从回形针音频附件中提取元数据,然后将其上传到S3,以便我可以显示比特率艺术家和音轨标题。这是我的track.rb模型。
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
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
end
在检查rails控制台的元数据(Track.last.metadata)后,控制台返回元数据的{}值。
当我使用
时<%= @track.audio.display_name %>