Skip to content

Instantly share code, notes, and snippets.

/bradoconnor.rb Secret

Created October 5, 2009 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/20b7ea938d7923944795 to your computer and use it in GitHub Desktop.
Save anonymous/20b7ea938d7923944795 to your computer and use it in GitHub Desktop.
#! /usr/bin/ruby
require 'optparse'
options = {}
optparse = OptionParser.new do |opts|
options[:operation] = 'add'
opts.on('--operation OPERATION') {|operation| options[:operation] = operation}
options[:time] = '00,000'
opts.on('--time TIME') {|time| options[:time] = time}
end
optparse.parse!
secs, millisecs = options[:time].split(",")
offset = secs.to_i * 1000 + millisecs.to_i
offset = -offset if options[:operation] == 'subtract'
files=[]
ARGV.each {|file| files << file}
srt_array=[]
srt_file = File.open(files[0],"r")
while line=srt_file.gets
srt_array < \d\d:\d\d:\d\d,\d\d\d/
times = line.chomp.split(/ --> /)
new_time = []
times.each do |time|
hours, mins, secs = time.split(":")
secs, millisecs = secs.split(",")
total_millisecs = hours.to_i * 3600000 + mins.to_i * 60000 + secs.to_i * 1000 + millisecs.to_i
total_millisecs += offset
total_millisecs = [0,total_millisecs].sort.last
hours, total_millisecs = total_millisecs.divmod(3600000)
mins, total_millisecs = total_millisecs.divmod(60000)
secs, millisecs = total_millisecs.divmod(1000)
new_time << ("%02d" % hours) + ":" + ("%02d" % mins) + ":" + ("%02d" % secs) + "," + ("%03d" % millisecs)
end
new_srt_array < " + new_time[1]
else
new_srt_array << line
end
end
output_file = File.new(files[1],"w")
output_file.puts new_srt_array
output_file.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment