-
Notifications
You must be signed in to change notification settings - Fork 0
/
soundManager.go
116 lines (106 loc) · 2.39 KB
/
soundManager.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"errors"
"github.com/faiface/beep"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
"os"
"time"
)
var (
soundInited = false
FileRegisteredError = errors.New("file already registered")
FileNotFoundError = errors.New("file not found")
SoundNotReadyError = errors.New("sound not ready")
)
type SoundInfo struct {
Key string
Path string
Handler *os.File
beep.Format
*beep.Buffer
Stream beep.StreamSeekCloser
Loaded, Ready bool
}
type SoundManager struct {
sounds map[string]*SoundInfo
}
func (receiver *SoundManager) Register(key string, path string, prefeth bool) error {
if _, ok := receiver.sounds[key]; ok {
return FileRegisteredError
}
f, err := os.Open(path)
if err != nil {
return err
}
streamer, format, err := receiver.decode(f, path)
if err != nil {
return err
}
info := SoundInfo{
Key: key,
Path: path,
Handler: f,
Format: format,
Buffer: nil,
Stream: streamer,
}
if prefeth {
info.Buffer = beep.NewBuffer(format)
info.Buffer.Append(info.Stream)
info.Stream.Close()
info.Handler.Close()
info.Stream = nil
info.Handler = nil
info.Loaded = true
}
receiver.sounds[key] = &info
info.Ready = true
return nil
}
func (receiver *SoundManager) Play(key string) error {
if soundInfo, ok := receiver.sounds[key]; ok {
if !soundInfo.Ready {
return SoundNotReadyError
}
if soundInfo.Loaded {
speaker.Play(soundInfo.Buffer.Streamer(0, soundInfo.Buffer.Len()))
} else {
speaker.Play(soundInfo.Stream)
}
} else {
return FileNotFoundError
}
return nil
}
func (receiver *SoundManager) Background(key string) error {
if soundInfo, ok := receiver.sounds[key]; ok {
if !soundInfo.Ready {
return SoundNotReadyError
}
if soundInfo.Loaded {
speaker.Play(soundInfo.Buffer.Streamer(0, soundInfo.Buffer.Len()))
} else {
speaker.Play(soundInfo.Stream)
}
} else {
return FileNotFoundError
}
return nil
}
func (receiver *SoundManager) decode(file *os.File, path string) (streamer beep.StreamSeekCloser, format beep.Format, err error) {
return mp3.Decode(file)
}
func NewSoundManager() (*SoundManager, error) {
if !soundInited {
format := beep.Format{}
format.SampleRate = 44100
err := speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/30))
if err != nil {
return nil, err
}
}
return &SoundManager{
sounds: make(map[string]*SoundInfo),
}, nil
}