This repository has been archived by the owner on May 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner.go
91 lines (76 loc) · 1.59 KB
/
runner.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"errors"
"sort"
"strconv"
)
type Runner struct {
lrc *Lrc
currentIndex int
offset bool
}
func NewRunner(lrc *Lrc, offset bool) *Runner {
return &Runner{
lrc: lrc,
currentIndex: -1,
offset: offset,
}
}
func (r *Runner) SetLrc(lrc *Lrc) {
r.lrc = lrc.Clone()
r.lrcUpdate()
}
func (r *Runner) lrcUpdate() {
if r.offset {
r.offsetAlign()
}
r.sortLyrics()
}
func (r *Runner) offsetAlign() {
if offset, exists := r.lrc.Info["offset"]; exists {
offsetValue, err := strconv.ParseFloat(offset, 64)
if err == nil {
r.lrc.Offset(offsetValue)
delete(r.lrc.Info, "offset")
}
}
}
func (r *Runner) sortLyrics() {
sort.SliceStable(r.lrc.Lyrics, func(i, j int) bool {
return r.lrc.Lyrics[i].Timestamp < r.lrc.Lyrics[j].Timestamp
})
}
func (r *Runner) TimeUpdate(timestamp float64) {
r.currentIndex = r.findIndex(timestamp, r.currentIndex)
}
func (r *Runner) findIndex(timestamp float64, startIndex int) int {
for i, lyric := range r.lrc.Lyrics {
if timestamp >= lyric.Timestamp {
startIndex = i
} else {
break
}
}
return startIndex
}
func (r *Runner) GetInfo() Info {
return r.lrc.Info
}
func (r *Runner) GetLyrics() []Lyric {
return r.lrc.Lyrics
}
func (r *Runner) GetLyric(index int) (Lyric, error) {
if index >= 0 && index < len(r.lrc.Lyrics) {
return r.lrc.Lyrics[index], nil
}
return Lyric{}, errors.New("index not exist")
}
func (r *Runner) CurIndex() int {
return r.currentIndex
}
func (r *Runner) CurLyric() (Lyric, error) {
return r.GetLyric(r.currentIndex)
}
func (r *Runner) Reset() {
r.currentIndex = -1
}