-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaudio.go
More file actions
200 lines (173 loc) · 4.8 KB
/
audio.go
File metadata and controls
200 lines (173 loc) · 4.8 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package pigo8
import (
"bytes"
"fmt"
"io/fs"
"log"
"path/filepath"
"strings"
"sync"
"github.com/hajimehoshi/ebiten/v2/audio"
"github.com/hajimehoshi/ebiten/v2/audio/wav"
)
const (
// sampleRate is the audio sample rate used for all audio playback
sampleRate = 44100
)
// audioPlayer manages the playback of audio files
type audioPlayer struct {
audioContext *audio.Context
musicPlayers map[int]*audio.Player
musicData map[int][]byte
mutex sync.Mutex
}
// Global audio player instance
var audioPlayerInstance *audioPlayer
var audioPlayerOnce sync.Once
// getAudioPlayer returns the singleton AudioPlayer instance
func getAudioPlayer() *audioPlayer {
audioPlayerOnce.Do(func() {
audioContext := audio.NewContext(sampleRate)
audioPlayerInstance = &audioPlayer{
audioContext: audioContext,
musicPlayers: make(map[int]*audio.Player),
musicData: make(map[int][]byte),
mutex: sync.Mutex{},
}
// Load all audio files at initialization
audioPlayerInstance.loadAudioFiles()
})
return audioPlayerInstance
}
// loadAudioFiles loads all audio*.wav files from the embedded resources
func (ap *audioPlayer) loadAudioFiles() {
// Skip if no custom resources are registered
if customResources == nil {
log.Println("No custom resources registered, skipping audio file loading")
return
}
// Walk through the embedded filesystem to find audio files
walkErr := fs.WalkDir(customResources.FS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// Skip directories
if d.IsDir() {
return nil
}
// Check if the file is a music*.wav file
if strings.HasPrefix(filepath.Base(path), "music") && strings.HasSuffix(path, ".wav") {
filename := filepath.Base(path)
var audioNumber int
// Extract the number from the filename (e.g., "music1.wav" -> 1)
_, err := fmt.Sscanf(filename, "music%d.wav", &audioNumber)
if err != nil {
log.Printf("Warning: Could not parse audio number from %s: %v", filename, err)
return nil
}
// Read the audio file
data, err := fs.ReadFile(customResources.FS, path)
if err != nil {
log.Printf("Warning: Could not read audio file %s: %v", path, err)
return nil
}
// Store the audio data
ap.musicData[audioNumber] = data
log.Printf("Loaded audio file: %s (ID: %d)", path, audioNumber)
}
return nil
})
if walkErr != nil {
log.Printf("Error walking through embedded filesystem: %v", walkErr)
}
log.Printf("Loaded %d audio files", len(ap.musicData))
}
// Music plays the audio file with the given ID.
// If n is -1, it stops all currently playing audio.
// If n is a valid audio ID, it plays that audio file.
// If exclusive is true, it stops all other audio files before playing.
func Music(n int, exclusive ...bool) {
if n == -1 {
// Special case: stop all music
StopMusic(-1)
return
}
// Default exclusive to false
shouldBeExclusive := len(exclusive) > 0 && exclusive[0]
ap := getAudioPlayer()
ap.mutex.Lock()
defer ap.mutex.Unlock()
// Stop other audio if requested
if shouldBeExclusive {
for _, player := range ap.musicPlayers {
if player != nil {
player.Pause()
if err := player.Rewind(); err != nil {
log.Printf("Error rewinding player: %v", err)
}
}
}
}
// Check if the audio file exists
audioData, exists := ap.musicData[n]
if !exists {
log.Printf("Warning: Audio file with ID %d not found", n)
return
}
// Check if this audio is already playing
player, exists := ap.musicPlayers[n]
if exists && player != nil {
if player.IsPlaying() {
// Already playing, do nothing
return
}
// Player exists but is not playing, rewind and play
if err := player.Rewind(); err != nil {
log.Printf("Error rewinding player: %v", err)
}
player.Play()
return
}
// Create a new player for this audio
reader := bytes.NewReader(audioData)
wavReader, err := wav.DecodeWithSampleRate(sampleRate, reader)
if err != nil {
log.Printf("Error decoding WAV file (ID: %d): %v", n, err)
return
}
player, err = ap.audioContext.NewPlayer(wavReader)
if err != nil {
log.Printf("Error creating audio player (ID: %d): %v", n, err)
return
}
// Store the player and play
ap.musicPlayers[n] = player
player.Play()
}
// StopMusic stops the audio file with the given ID
// If id is -1, it stops all audio files
func StopMusic(id int) {
ap := getAudioPlayer()
ap.mutex.Lock()
defer ap.mutex.Unlock()
if id == -1 {
// Stop all audio
for _, player := range ap.musicPlayers {
if player != nil {
player.Pause()
if err := player.Rewind(); err != nil {
log.Printf("Error rewinding player: %v", err)
}
}
}
return
}
// Stop specific audio
player, exists := ap.musicPlayers[id]
if exists && player != nil {
player.Pause()
if err := player.Rewind(); err != nil {
log.Printf("Error rewinding player: %v", err)
}
}
}