Sha256: 62301d5ddeac8046d594766eb3f4072ef50f267e8e7182ecff50343e63124283

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

require "fileutils"

module CarrierWave
  module Ffmpeg
    module Audio
      class Processor
        DefaultOptions = {
          bit_rate: "128k",
          sample_rate: "44100",
        }

        # Scope these under Processor so you can catch the ones generated by just this class.
        class RuntimeError < ::RuntimeError;end;
        class ArgumentError < ::ArgumentError;end;

        class << self
          def convert(source, options)
            options = DefaultOptions.merge(options)
            final_filename = tmp_filename(source: source, format: "mp3")
            system "ffmpeg -loglevel fatal -i #{source} -c:a libmp3lame -ab #{options[:bit_rate]} -ar #{options[:sample_rate]} #{final_filename}"
            final_filename
          end

          def watermark(source, options)
            options = DefaultOptions.merge(options)
            watermark_file_path = options[:watermark_file]

            raise ArgumentError.new("No watermark filename given, must be a path to an existing sound file.") unless watermark_file_path
            raise RuntimeError.new("Watermark file '#{watermark_file_path}' not found.") unless File.exist?(watermark_file_path)

            final_filename = tmp_filename(source: source, format: "mp3", prefix: "wtmk")
            system "ffmpeg -loglevel fatal -i #{source} -i #{watermark_file_path} -filter_complex amerge -c:a libmp3lame -ab #{options[:bit_rate]} -ar #{options[:sample_rate]} #{final_filename}"

            final_filename
          end

          private

          # Generate a temporary filename
          def tmp_filename source:, format:, prefix: nil
            ext = File.extname(source)
            source_filename_without_ext = File.basename(source, ext)
            File.join File.dirname(source), "tmp#{prefix.present? ? '_' + prefix : ''}_#{source_filename_without_ext}_#{Time.now.to_i}.#{format}"
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
carrierwave-ffmpeg-audio-0.1.2 lib/carrierwave/ffmpeg/audio/processor.rb