forked from And678/goPlayer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sound.go
67 lines (60 loc) · 1.33 KB
/
sound.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
package main
import (
"github.com/faiface/beep"
"github.com/faiface/beep/effects"
"github.com/faiface/beep/flac"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
"github.com/faiface/beep/wav"
"os"
"path/filepath"
"time"
)
var supportedFormats = []string{".mp3", ".wav", ".flac"}
var mainCtrl *beep.Ctrl
var s beep.StreamSeekCloser
var format beep.Format
var volume = &effects.Volume{
Base: 2,
}
func playSong(input Song) (int, error) {
f, err := os.Open(input.path)
if err != nil {
return 0, err
}
switch fileExt := filepath.Ext(input.path); fileExt {
case ".mp3":
s, format, err = mp3.Decode(f)
case ".wav":
s, format, err = wav.Decode(f)
case ".flac":
s, format, err = flac.Decode(f)
}
if err != nil {
return 0, err
}
volume.Streamer = s
mainCtrl = &beep.Ctrl{Streamer: volume}
speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
speaker.Play(mainCtrl)
return int(float32(s.Len()) / float32(format.SampleRate)), nil
}
func pauseSong(state bool) {
speaker.Lock()
mainCtrl.Paused = state
speaker.Unlock()
}
func seek(pos int) error {
speaker.Lock()
err := s.Seek(pos * int(format.SampleRate))
speaker.Unlock()
return err
}
func setVolue(percent int) {
if percent == 0 {
volume.Silent = true
} else {
volume.Silent = false
volume.Volume = -float64(100-percent) / 100.0 * 5
}
}