With ActiveStorage, storing files in Rails is made easier.
However, when it comes to audio files, it’s often necessary to go beyond simple storage and analyze the audio content itself.
To achieve this, integrating a media stream analyzer into a Rails application can be incredibly valuable.
For this, we can use the ffprobe which is already used by the Rails analyzer to extract basic information about the media file.
How does the Rails Analyzer work?
Rails has three analyzers to extract metadata of a blob, they are AudioAnalyzer, ImageAnalyzer, and VideoAnalyzer.
It also has NullAnalyzer which will be used if content type is not detected.
analyze method is called which is a method in ActiveStorage::Blob::Analyzable module.
It will first detect the analyzer class based on the content type, then analyzer will then extract metadata using ffprobe(for audio and video) or ImageMagick(for image) and will update the blob record with the extracted metadata.
We can use the streamio-ffmpeg gem which is a ffmpeg wrapper to extract these details in Ruby.
Running the blob
analyze method will only add
bit_rate in metadata.
With this change audio analyzer will now return
sample rate along with information like
bit rate, and
In the upcoming Rails version (I have used Rails 7.1.0 alpha), when the blob is created we can run the
analyze method which will also add the
sample rate in the metadata.