-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlrc_timer.go
71 lines (56 loc) · 1.22 KB
/
lrc_timer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package lyrics_lrc
import "time"
type LRCTimer struct {
file *LRCFile
timer *time.Timer
stop bool
listeners []func(startTimeMs int64, content string, last bool)
}
func NewLRCTimer(file *LRCFile) (timer *LRCTimer) {
timer = &LRCTimer{
file: file,
}
return
}
func (t *LRCTimer) AddListener(l func(startTimeMs int64, content string, last bool)) {
t.listeners = append(t.listeners, l)
}
func (t *LRCTimer) Start() {
fragments := t.file.fragments
if len(fragments) < 1 {
return
}
currentIdx := 0
current := fragments[0]
startTime := time.Now()
t.timer = time.NewTimer(time.Millisecond * time.Duration(current.StartTimeMs))
t.stop = false
for {
<-t.timer.C
if t.stop {
break
}
currentIdx++
last := currentIdx >= len(fragments)
for _, l := range t.listeners {
go l(current.StartTimeMs, current.Content, last)
}
if last {
break
}
current = fragments[currentIdx]
elapsedTime := time.Now().Sub(startTime)
t.timer.Reset((time.Millisecond * time.Duration(current.StartTimeMs)) - elapsedTime)
}
t.timer.Stop()
t.timer = nil
}
func (t LRCTimer) IsStarted() bool {
return t.timer != nil
}
func (t LRCTimer) Stop() {
t.stop = true
if t.timer != nil {
t.timer.Stop()
}
}