Skip to content

Enables ActiveStorage variants for other file types than images, such as audio or video files, through an API for registering custom transformers similar to previewers.

License

Notifications You must be signed in to change notification settings

jetthoughts/activestorage-autobots

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gem Version Build

ActiveStorage Autobots (aka ActiveStorage Transformers)

Enables ActiveStorage variants for other file types than images, such as audio or video files, through an API for registering custom transformers similar to previewers.

This will provide for you to add ffmpeg or other transformers to pre-process video, audio files.

Installation

Add this line to your application's Gemfile:

gem 'activestorage-autobots'

And then execute:

$ bundle

Usage

# lib/active_storage/transformers/ffmpeg_transformer.rb

require 'active_storage/transformers/transformer'

class ActiveStorage::Transformers::FFMPEGTransformer < ActiveStorage::Transformers::Transformer
  def self.accept?(blob)
    blob.video? || blob.audio?
  end

  def transform(input, format:)
    format ||= File.extname(input.path)
    options = transformations[:ffmpeg_opts]
    create_tempfile(ext: format) do |output|
      system "ffmpeg -y -i #{input.path} #{options} #{output.path}", exception: true
      yield output
    end
  end

  def create_tempfile(ext: '')
    ext = ".#{ext}" unless ext.blank? || ext.start_with?('.')
    tempfile = Tempfile.new(['active_storage_transformer_', ext], binmode: true)
    yield tempfile
  ensure
    tempfile.close!
  end
end

Update in initializers

# config/initializers/active_storage.rb

require 'active_storage/transformers/ffmpeg_transformer'

ActiveStorage.transformers << ActiveStorage::Transformers::FFMPEGTransformer
# => [ ActiveStorage::Transformers::ImageProcessingTransformer, FFMPEGTransformer ]
<%= audio_tag(
      user.my_audio.variant(
        ffmpeg_opts: "-af silenceremove=stop_periods=-1:stop_duration=1:stop_threshold=-90dB",
        format: "mp3"
      )
    ) %>

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/jetthoughts/activestorage-autobots. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

About

Enables ActiveStorage variants for other file types than images, such as audio or video files, through an API for registering custom transformers similar to previewers.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages