簡體   English   中英

RoR TagLib-Ruby:如何在數據庫中設置ID3標簽

[英]RoR TagLib-Ruby: How to set ID3 tags in DB

感謝您的任何幫助。

我想將數據庫中的id3標簽數據設置為模型MasterSong的屬性。 具體來說,標題,藝術家和專輯。

create_table :master_songs do |t|
  t.integer :user_id
  t.has_attached_file :m_song
 **- t.string :title
 - t.string :artist
 - t.string :album**

在我的模型中,我使用回調在保存對象(master_song)之前設置數據。

before_save :set_id3_tags_in_database

def set_id3_tags_in_database
TagLib::MPEG::File.open(self.m_song.path) do |file|
   tag = file.id3v2_tag
   tag.title
   tag.album
   tag.artist
end
  self.update_attributes(:title => tag.title,
  :artist => tag.artist,
  :album => tag.album)
end

我很確定我的語法是問題。 該對象似乎出現錯誤

undefined method `title' for nil:NilClass with an infinite loop

控制器創建動作正常:

 def create
   @master_song = current_user.master_songs.build(params[:master_song])

   respond_to do |format|
    if @master_song.save
     format.html { redirect_to @master_song, notice: 'Master song was successfullycreated.' }
   end

我在這里做錯了什么? 更新:def set_id3_tags z = TagLib :: MPEG :: File.open(self.m_song.path)做| file | tag = file.id3v2_tag tag.title結束self.update_attribute!(:title => z)結束

現在獲取堆棧級別太深的錯誤。

首先,請確保self.m_song.path是正確的路徑,並且在那里存在文件。

接下來,下面這行:

tag = file.id3v2_tag

當文件還沒有標簽時不創建標簽,因此可能返回nil。 將可選參數“ create”設置為true可以自動創建標簽:

tag = file.id3v2_tag(true)

好的,那么看來,設置完標記數據后,您想保存它。 為此,您必須像下面這樣顯式調用save(注意該塊的最后一行):

TagLib::MPEG::File.open(self.m_song.path) do |file|
   tag = file.id3v2_tag(true)
   # set data
   file.save
end

有關更多信息,請參見此處的文檔: http : //rubydoc.info/gems/taglib-ruby/frames

好! 所以我做到了,玩了又玩又玩。

def set_id3_tags
z = TagLib::MPEG::File.open(self.m_song.path) do |file|
 unless tag.nil?
  tag = file.id3v2_tag
  self.title = tag.title
  self.album = tag.album
  self.artist = tag.artist

  else
end

結束

添加if title.nil? 為我做了。 回調很奇怪,但絕對有價值。 希望這對其他人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM