Get mp3 duration when uploading to S3 using carrie

2019-07-06 03:49发布

问题:

I am writing an application and its basically a music platform. I would like to get the duration of the mp3 through its metadata and save it in a table before i upload it to S3.

I am using a combination of carrierwave and fog gems to upload. What is the recommended way of extracting the mp3 metadata for saving to database?

回答1:

There is a gem for such operations taglib-ruby

here is an example

  def set_duration
    # :duration is an integer
    # t.integer  "duration",                  :default => 0
    TagLib::FileRef.open(file.file.path) do |file|
      update_column(:duration, file.audio_properties.length) unless file.null?
    end
  end 

Of course you will have your own attr names, but in general should work.