Rails 7.1 adds an option to extract the sample rate of an audio file
Active Storage is a powerful file attachment system for Rails applications. It simplifies uploading and storing files in the cloud, making managing and retrieving files from your applications easier. Active Storage can upload, store, and retrieve audio files in your Rails application. You can also transform and generate representations of audio files, such as extracting metadata or converting formats.
You might need audio metadata in advance when working with them. You need to integrate a media stream analyzer into your Rails application to extract the details. Rails uses ffprober that gathers information from multimedia streams and prints it in human and machine-readable fashion.
Before Rails 7.1
Prior to Rails 7.1, to get the sample rate of an audio file, you need to first download the file. Next, you must pass the file to the ffprober to get the sample rate.
ffprobe = Ffprober::Parser.from_file("audio_file.mp3")
ffprobe.audio_streams.count
=> 1
ffprobe.audio_streams.first.sample_rate
=> 44100
You can use
streamio-ffmpeg gem
instead of ffprober
.
blob = ActiveStorage::Blob.find_by(filename: "audio_file.mp3")
path = ActiveStorage::Blob.service.path_for(blob.key)
result = FFMPEG::Movie.new(path)
result.audio_sample_rate
# 44100
You can run the analyze
method on the blob
and
then execute metadata
on blob,
it would return duration
and
bit_rate
details.
blob.analyze
blob.metadata
=> {"analyzed"=>true, "bit_rate"=>144000, "duration"=>0.54012, "identified"=>true}
In Rails 7.1
Rails 7.1 adds an option to extract the sample rate
of an audio file.
On executing the analyze
and
metadata
methods on the blob,
you can fetch the sample_rate
.
blob = ActiveStorage::Blob.create_and_upload!(
io: File.open("#{Rails.root}/audio.mp3"),
filename: "audio_file.mp3",
content_type: "audio"
)
blob.analyze
blob.metadata
=> {"analyzed"=>true, "sample_rate"=> 44100, "bit_rate"=>144000, "duration"=>0.54012, "identified"=>true}
blob.metadata[:sample_rate]
=> 44100
To know more about this feature, please refer to this PR.