77 lines
1.5 KiB
Go
77 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"embed"
|
|
"fmt"
|
|
"log"
|
|
"sync"
|
|
|
|
"github.com/hajimehoshi/ebiten/v2/audio"
|
|
"github.com/hajimehoshi/ebiten/v2/audio/wav"
|
|
)
|
|
|
|
//go:embed assets/audio
|
|
var audioAssets embed.FS
|
|
|
|
type audioID int
|
|
|
|
type audioAtlas struct {
|
|
ctx *audio.Context
|
|
atlas map[audioID]*audio.Player
|
|
sync.RWMutex
|
|
}
|
|
|
|
func newAudioAtlas(ctx *audio.Context) *audioAtlas {
|
|
return &audioAtlas{
|
|
ctx: ctx,
|
|
atlas: make(map[audioID]*audio.Player),
|
|
}
|
|
}
|
|
|
|
// loadWAV loads a WAV formatted audio file into the atlas.
|
|
func (a *audioAtlas) loadWAV(id audioID, filePath string) error {
|
|
f, err := audioAssets.Open("assets/audio/" + filePath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer f.Close()
|
|
|
|
stream, err := wav.DecodeWithSampleRate(a.ctx.SampleRate(), f)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
player, err := a.ctx.NewPlayer(stream)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Workaround to prevent delays when playing for the first time.
|
|
player.SetVolume(0)
|
|
player.Play()
|
|
player.Pause()
|
|
player.Rewind()
|
|
player.SetVolume(1)
|
|
|
|
a.atlas[id] = player
|
|
return nil
|
|
}
|
|
|
|
// playAudio rewinds and starts an audio player from the atlas.
|
|
func (a *audioAtlas) getAudio(id audioID) *audio.Player {
|
|
return a.atlas[id]
|
|
}
|
|
|
|
// playAudio rewinds and starts an audio player from the atlas.
|
|
func (a *audioAtlas) playAudio(id audioID) error {
|
|
player := a.getAudio(id)
|
|
if player == nil {
|
|
return fmt.Errorf("unknown audio ID %d", id)
|
|
}
|
|
log.Println(player)
|
|
player.Pause()
|
|
player.Rewind()
|
|
player.Play()
|
|
return nil
|
|
}
|