-
Notifications
You must be signed in to change notification settings - Fork 0
/
sound.go
108 lines (89 loc) · 2 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
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
package main
import (
"fmt"
"os"
"path/filepath"
"time"
"github.com/faiface/beep"
"github.com/faiface/beep/effects"
"github.com/faiface/beep/speaker"
"github.com/faiface/beep/wav"
)
var (
mainTrackStreamer beep.Streamer
sounds = make(map[Track]*beep.Buffer)
hasErrored = false
)
type Track string
const (
hurtSound Track = "hurt"
attackSound Track = "attack1"
coinPickupSound Track = "coinpickup"
deniedSound Track = "denied"
projectile1Sound Track = "projectile1"
projectile2Sound Track = "projectile2"
rumbleSound Track = "rumble"
explosionSound Track = "explosion"
rocketLauncherSound Track = "rocket"
gunSound Track = "gun"
)
func SetupAudio() {
mainTrack, err := os.Open(filepath.Join(binPath, "assets/audio/mainTrack.wav"))
if err != nil {
hasErrored = true
return
}
streamer, format, err := wav.Decode(mainTrack)
if err != nil {
hasErrored = true
return
}
if err := speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10)); err != nil {
hasErrored = true
return
}
mainTrackStreamer = &effects.Volume{
Streamer: beep.Loop(-1, streamer),
Base: 2,
Volume: -3,
}
speaker.Play(mainTrackStreamer)
loadSound(hurtSound)
loadSound(attackSound)
loadSound(coinPickupSound)
loadSound(deniedSound)
loadSound(projectile1Sound)
loadSound(projectile2Sound)
loadSound(rumbleSound)
loadSound(explosionSound)
loadSound(rocketLauncherSound)
loadSound(gunSound)
}
func loadSound(sound Track) {
filename := filepath.Join(binPath, "assets", "audio", fmt.Sprintf("%s.wav", sound))
f, err := os.Open(filename)
if err != nil {
panic(err)
return
}
defer f.Close()
streamer, format, err := wav.Decode(f)
if err != nil {
panic(err)
return
}
buffer := beep.NewBuffer(format)
buffer.Append(streamer)
_ = streamer.Close()
sounds[sound] = buffer
}
func PlaySound(sound Track) {
if hasErrored {
return
}
b, ok := sounds[sound]
if !ok {
return
}
speaker.Play(b.Streamer(0, b.Len()))
}