/
audio.go
77 lines (65 loc) · 1.48 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 mypong
import (
"bytes"
"embed"
"github.com/hajimehoshi/ebiten/v2/audio"
"github.com/hajimehoshi/ebiten/v2/audio/mp3"
)
const SAMPLERATE = 48000
//go:embed sounds/*
var sounds embed.FS // Intégrer un répertoire entier
var (
// audio context
audioContext *audio.Context = audio.NewContext(SAMPLERATE)
// raw mp3 bytes for boing
audioDataBoing []byte
// player for rain
audioPlayerRain *audio.Player
)
func init() {
var err error
// Load data for boieng
audioDataBoing, err = sounds.ReadFile("sounds/boing.mp3")
if err != nil {
panic(err)
}
// create a single player for background
data, err := sounds.ReadFile("sounds/chase.mp3")
if err != nil {
panic(err)
}
d, err := mp3.DecodeWithSampleRate(SAMPLERATE, bytes.NewReader(data))
if err != nil {
panic(err)
}
audioPlayerRain, err = audioContext.NewPlayer(d)
if err != nil {
panic(err)
}
// Play sounds
UpdateAudioBackground()
// PlayAudioBoing()
}
// PlayAudioBoing creates a player and plays the boing file
func PlayAudioBoing() {
d, err := mp3.DecodeWithSampleRate(SAMPLERATE, bytes.NewReader(audioDataBoing))
if err != nil {
panic(err)
}
p, err := audioContext.NewPlayer(d)
if err != nil {
panic(err)
}
if p != nil {
p.Rewind()
p.Play()
}
}
// Plays rain sound in a loop, using a single player
// Should be called within the update loop.
func UpdateAudioBackground() {
if audioPlayerRain != nil && !audioPlayerRain.IsPlaying() {
audioPlayerRain.Rewind()
audioPlayerRain.Play()
}
}