2020-01-31 23:18:11 -05:00
|
|
|
package ebiten
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
|
2020-02-01 18:55:56 -05:00
|
|
|
"github.com/OpenDiablo2/OpenDiablo2/d2core/d2asset"
|
2020-02-01 20:39:28 -05:00
|
|
|
"github.com/OpenDiablo2/OpenDiablo2/d2core/d2audio"
|
2020-01-31 23:18:11 -05:00
|
|
|
"github.com/hajimehoshi/ebiten/audio/wav"
|
|
|
|
|
|
|
|
"github.com/hajimehoshi/ebiten/audio"
|
|
|
|
)
|
|
|
|
|
2020-02-01 21:51:49 -05:00
|
|
|
type AudioProvider struct {
|
2020-01-31 23:18:11 -05:00
|
|
|
audioContext *audio.Context // The Audio context
|
|
|
|
bgmAudio *audio.Player // The audio player
|
|
|
|
lastBgm string
|
|
|
|
sfxVolume float64
|
|
|
|
bgmVolume float64
|
|
|
|
}
|
|
|
|
|
2020-02-01 21:51:49 -05:00
|
|
|
func CreateAudio() (*AudioProvider, error) {
|
|
|
|
result := &AudioProvider{}
|
2020-01-31 23:18:11 -05:00
|
|
|
var err error
|
|
|
|
result.audioContext, err = audio.NewContext(44100)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2020-02-01 21:51:49 -05:00
|
|
|
func (eap *AudioProvider) PlayBGM(song string) {
|
2020-01-31 23:18:11 -05:00
|
|
|
if eap.lastBgm == song {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
eap.lastBgm = song
|
|
|
|
if song == "" && eap.bgmAudio != nil && eap.bgmAudio.IsPlaying() {
|
|
|
|
_ = eap.bgmAudio.Pause()
|
|
|
|
return
|
|
|
|
}
|
2020-02-08 21:02:37 -05:00
|
|
|
|
|
|
|
if eap.bgmAudio != nil {
|
|
|
|
err := eap.bgmAudio.Close()
|
2020-01-31 23:18:11 -05:00
|
|
|
if err != nil {
|
2020-02-08 21:02:37 -05:00
|
|
|
log.Panic(err)
|
2020-01-31 23:18:11 -05:00
|
|
|
}
|
2020-02-08 21:02:37 -05:00
|
|
|
}
|
|
|
|
audioData, err := d2asset.LoadFile(song)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
d, err := wav.Decode(eap.audioContext, audio.BytesReadSeekCloser(audioData))
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
s := audio.NewInfiniteLoop(d, d.Length())
|
|
|
|
eap.bgmAudio, err = audio.NewPlayer(eap.audioContext, s)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
eap.bgmAudio.SetVolume(eap.bgmVolume)
|
|
|
|
// Play the infinite-length stream. This never ends.
|
|
|
|
err = eap.bgmAudio.Rewind()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
err = eap.bgmAudio.Play()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2020-01-31 23:18:11 -05:00
|
|
|
}
|
|
|
|
|
2020-02-01 21:51:49 -05:00
|
|
|
func (eap *AudioProvider) LoadSoundEffect(sfx string) (d2audio.SoundEffect, error) {
|
2020-01-31 23:18:11 -05:00
|
|
|
result := CreateSoundEffect(sfx, eap.audioContext, eap.sfxVolume) // TODO: Split
|
|
|
|
return result, nil
|
|
|
|
}
|
|
|
|
|
2020-02-01 21:51:49 -05:00
|
|
|
func (eap *AudioProvider) SetVolumes(bgmVolume, sfxVolume float64) {
|
2020-01-31 23:18:11 -05:00
|
|
|
eap.sfxVolume = sfxVolume
|
|
|
|
eap.bgmVolume = bgmVolume
|
|
|
|
}
|