/
player_contrl.go
84 lines (75 loc) · 1.6 KB
/
player_contrl.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
package main
import (
"fmt"
"github.com/ns-cn/e9i/command"
"github.com/ns-cn/e9i/loop"
"log"
"math/rand"
"net/http"
"time"
"github.com/faiface/beep"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
)
var playlist = make([]Song, 0)
var current = 0
var currentSong = Song{}
var loopType = loop.LOOP_QUEUE
var actionChan = make(chan int)
var OnProcessing = false
var paused = false
func Loop() {
for {
select {
case action := <-actionChan:
if action == command.PLAYNEXT {
if loopType != loop.NONE {
refreshNextIndex(1)
go Play(playlist[current])
RefreshSearchList()
}
}
}
}
}
func refreshNextIndex(offset int) {
size := len(playlist)
if loopType == loop.LOOP_QUEUE {
current = (current + offset + size) % size
} else if loopType == loop.LOOP_RANDOM {
current = rand.Intn(size)
}
}
func Play(song Song) {
currentSong = song
url := song.GetPath()
fmt.Println(fmt.Sprintf("%s:%s -> %s", song.Name, song.ID, url))
// Download the MP3 file
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Decode the MP3 file
streamer, format, err := mp3.Decode(resp.Body)
if err != nil {
log.Fatal(err)
}
sr := format.SampleRate * 2
OnProcessing = true
paused = false
_ = speaker.Init(sr, sr.N(time.Second/100))
resampled := beep.Resample(4, format.SampleRate, sr, streamer)
// Play the audio
done := make(chan bool)
speaker.Clear()
speaker.Play(beep.Seq(resampled, beep.Callback(func() {
actionChan <- command.PLAYNEXT
OnProcessing = false
done <- true
})))
go func() {
RefreshSearchList()
}()
<-done
}