-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaudio.go
76 lines (68 loc) · 1.63 KB
/
audio.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
// +build !gen
package main
import (
"fmt"
"github.com/faiface/beep"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
"io"
"os"
"strings"
"time"
)
type NotifySound struct {
buffer *beep.Buffer
name string
format beep.Format
}
var currentSound NotifySound
func setSoundFromDisk(path string) error {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("error loading sound: %w", err)
}
defer f.Close()
return setSound(f, path)
}
func setSoundBuiltin(name string) error {
if name == "" || name == "none" {
setSoundNone()
return nil
}
f, err := BinFS.Open("assets/sounds/" + name + ".mp3")
if err != nil {
return err
}
return setSound(f, name)
}
func builtInSounds() (results []string) {
for _, file := range BinFS.Files {
if strings.HasSuffix(file.Filename, ".mp3") {
results = append(results, strings.TrimSuffix(file.Filename, ".mp3"))
}
}
return results
}
func setSoundNone() {
currentSound = NotifySound{name: "none"}
}
func setSound(data io.ReadCloser, name string) error {
streamer, format, err := mp3.Decode(data)
currentSound = NotifySound{name: name, format: format, buffer: beep.NewBuffer(format)}
if err != nil {
return fmt.Errorf("error decoding sound: %w", err)
}
currentSound.buffer.Append(streamer)
return streamer.Close()
}
func playSound() {
if currentSound.buffer != nil {
err := speaker.Init(currentSound.format.SampleRate, currentSound.format.SampleRate.N(time.Second/10))
if err != nil {
fmt.Fprintln(os.Stderr, "failed to init speaker for sound: ", err)
return
}
sound := currentSound.buffer.Streamer(0, currentSound.buffer.Len())
speaker.Play(sound)
}
}