ffmpeg コマンドを ruby で扱う

popen で ffmpeg コマンドを読んでいるだけです。
普段使っているオーディオファイル変換と iPod touch 用に変換するプロファイルを用意した。
コマンドライン引数を保存する @option を直接アクセスできるようにした方がよかったかも。

2007/12/09 改修するかな


class FFmpegHelper
  def initialize(file)
    @profile = {
      :ipod_touch => {
        :f       => 'mp4',
        :vcodec  => 'h264',
        :s       => '320x240',
        :b       => 512,
        :bt      => '512k',
        :acodec  => 'aac',
        :ac      => 2,
        :ab      => '128k',
      },
      :audio => {
        :ac      => 2,
        :ab      => '128k',
        :ar      => 44100,
      },
    }
    @option = {}

    @file = file
  end

  def set_profile(name)
    if @profile.key?(name)
      @option.merge!(@profile[name])
    else
      printf $stderr, "not found profile; #{name}\n"
    end
  end

  def set_option(opt)
    @option.merge!(opt)
  end

  def execute(infile, outfile)
    argument = []

    argument << %Q{#{@file} -y -i "#{infile}" }

    @option.each {|k, v|
      argument << "-#{k} #{v} "
    }

    argument << %Q{"#{outfile}" 2>&1}

    command = argument.join('')

    puts "#{command}"

    io = IO.popen("#{command}", "r");
    io.each("\r") {|line|
      puts line
    }
    io.close
  end
end

if $0 == __FILE__

  ffmpeg = FFmpegHelper.new('D:/home/opt/bin/ffmpeg')

  ffmpeg.set_profile(:ipod_touch)

  ffmpeg.set_option({
    :title     => %Q{"foobar"},
    :timestamp => %Q{"#{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"},
  })

  ffmpeg.execute('foobar.flv', 'foobar.mp4')
end