Class: WebVTT::Timestamp

Inherits:
Object
  • Object
show all
Defined in:
lib/vtt/timestamp.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(time) ⇒ Timestamp



24
25
26
27
28
29
30
31
32
# File 'lib/vtt/timestamp.rb', line 24

def initialize( time )
  if time.to_s =~ /^\d+([.]\d*)?$/
    @timestamp = time
  elsif time.is_a? String
    @timestamp = Timestamp.parse_seconds( time )
  else
    raise ArgumentError.new("time not Fixnum nor a string")
  end
end

Class Method Details

.parse_seconds(timestamp) ⇒ Object

时间戳转换成秒



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/vtt/timestamp.rb', line 10

def self.parse_seconds( timestamp )
  if mres = timestamp.match(/\A([0-9]{2}):([0-9]{2}):([0-9]{2}\.[0-9]{3})\z/)
    sec = mres[3].to_f 
    sec += mres[2].to_f * 60 
    sec += mres[1].to_f * 60 * 60 
  elsif mres = timestamp.match(/\A([0-9]{2}):([0-9]{2}\.[0-9]{3})\z/)
    sec = mres[2].to_f 
    sec += mres[1].to_f * 60
  else
    raise ArgumentError.new("Invalid WebVTT timestamp format: #{timestamp.inspect}")
  end
  return sec
end

Instance Method Details

#+(other) ⇒ Object

秒向前滚动



71
72
73
# File 'lib/vtt/timestamp.rb', line 71

def +(other)
  Timestamp.new self.to_f + other.to_f
end

#hms_resultObject

小时结果输出



57
58
59
60
61
62
63
# File 'lib/vtt/timestamp.rb', line 57

def hms_result
	if @timestamp > 3600
			 sprintf("%02d:%02d:%02d.%03d", *@hms)
		else
			 sprintf("%02d:%02d.%03d", *@hms)
		end
end

#hms_startObject

小时判断



48
49
50
51
52
53
54
# File 'lib/vtt/timestamp.rb', line 48

def hms_start
	if @timestamp > 3600
			@round = Array.new 2,60
		else
			@round = Array.new 1,60
		end
end

#to_fObject

秒类型转换fixnum



66
67
68
# File 'lib/vtt/timestamp.rb', line 66

def to_f
  @timestamp.to_f
end

#to_hmsObject

小时分秒转换



40
41
42
43
44
45
# File 'lib/vtt/timestamp.rb', line 40

def to_hms
  hms_start
  @hms = @round.reduce( [ @timestamp ] ) { |m,o|m.unshift(m.shift.divmod(o)).flatten }
  @hms << (@timestamp.divmod(1).last * 1000).round
  hms_result
end

#to_sObject

输出类型转换城string



35
36
37
# File 'lib/vtt/timestamp.rb', line 35

def to_s
  @timestamp.to_s
end