Rails 7.1 adds an option to extract the sample rate of an audio file

railsNovember 08, 2023Dotby Alkesh Ghorpade

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.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at [email protected] or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right