Skip to content

Instantly share code, notes, and snippets.

@hyperqube
Created September 9, 2012 02:34
Show Gist options
  • Save hyperqube/3682201 to your computer and use it in GitHub Desktop.
Save hyperqube/3682201 to your computer and use it in GitHub Desktop.
Assemble m4a files into audio books
require 'pp'
require 'fileutils'
require 'escape'
@TARGET = ARGV[0]
File.delete(@TARGET) if File.exists?(@TARGET)
def formatTime(dur)
ms = ((dur.round(3) - dur.truncate())*1000).to_i
totalss = dur.truncate().to_i
ss = totalss.modulo(60)
mm = (totalss.-(ss)/60).modulo(60)
hh = (totalss/3600)
"%02d:%02d:%02d.%03d" % [hh,mm,ss,ms]
end
def getLengthMP4(f)
cmd = Escape.shell_command [ :mp4info , f]
/(\d*.\d{3}) secs/ =~ `#{cmd}`
$1.to_f
end
class Chapter
def initialize(filepath)
@filepath = filepath
@length = getLengthMP4(self.filepath)
@offset = @@offset
@@offset += @length
@name = self.name()
end
attr_reader :offset , :filepath
def name
@filepath.gsub( /.m..$/,'')
end
def formatted_offset
formatTime(@offset)
end
def chapter_entry
formatted_offset + ' ' + name
end
end
def append
0.step(@chlst.size-1,20) do |i|
ubound = [i+19,@chlst.size-1].min
iflag = i.upto(ubound).map do |j|
[ '-cat', @chlst.at(j).filepath ]
end.flatten
cmda = [:mp4box, iflag].flatten
cmda+=["-new"] if i < 20
cmda+=[@TARGET]
cmd = Escape.shell_command cmda
p cmd
puts `#{cmd}`
end
end
def chapterFile
chfilename = @TARGET.gsub(/\.m..$/i,'.chapters.txt')
File.open(chfilename,'w+') do |cf|
cf.puts @chlst.map{ |f| f.chapter_entry }.*("\n")
end
end
glob_pattern = '**/*.m4a'
@@offset = 0.0
@chlst = Dir.glob( glob_pattern ).sort.map{ |f| Chapter.new f}
pp @chlst
append
markChapters = Escape.shell_command [:mp4chaps, "-i" , "-Q", @TARGET]
chapterFile
puts `#{markChapters}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment