-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio.go
77 lines (60 loc) · 1.31 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
77
package main
import (
"embed"
"errors"
"fmt"
"log"
"time"
"github.com/gopxl/beep"
"github.com/gopxl/beep/mp3"
"github.com/gopxl/beep/speaker"
)
type Audio interface {
register(name string, filepath string) error
play(name string) error
}
type audio struct {
registry map[string]*beep.Buffer
}
var SAMPLE_RATE beep.SampleRate = 44100
func newAudio() *audio {
err := speaker.Init(SAMPLE_RATE, SAMPLE_RATE.N(time.Second/10))
if err != nil {
log.Fatal(err)
}
return &audio{
registry: make(map[string]*beep.Buffer),
}
}
//go:embed assets/sounds/*
var assets embed.FS
func (a *audio) register(name string, filename string) error {
f, err := assets.Open(fmt.Sprintf("assets/sounds/%s", filename))
if err != nil {
return err
}
streamer, format, err := mp3.Decode(f)
if err != nil {
log.Fatal(err)
}
buffer := beep.NewBuffer(format)
buffer.Append(streamer)
streamer.Close()
a.registry[name] = buffer
return nil
}
func (a *audio) play(name string) error {
buffer, ok := a.registry[name]
if !ok {
return errors.New("Not found")
}
format := buffer.Format()
streamer := buffer.Streamer(0, buffer.Len())
if format.SampleRate == SAMPLE_RATE {
speaker.Play(streamer)
} else {
resampler := beep.Resample(4, format.SampleRate, SAMPLE_RATE, streamer)
speaker.Play(resampler)
}
return nil
}