65 lines
979 B
Go
65 lines
979 B
Go
package audio
|
|
|
|
import (
|
|
"github.com/ebitengine/oto/v3"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
hasSetup = false
|
|
audio Audio
|
|
)
|
|
|
|
type Audio struct {
|
|
AudioContext *oto.Context
|
|
}
|
|
|
|
func setup() {
|
|
var ctxOptions = oto.NewContextOptions{
|
|
SampleRate: 44100,
|
|
ChannelCount: 2,
|
|
Format: oto.FormatSignedInt16LE,
|
|
BufferSize: 0,
|
|
}
|
|
|
|
var ready = make(chan struct{})
|
|
var err error
|
|
audio.AudioContext, ready, err = oto.NewContext(&ctxOptions)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
<-ready // Wait for the context to be ready
|
|
}
|
|
|
|
func Play() {
|
|
if !hasSetup {
|
|
setup()
|
|
hasSetup = true
|
|
}
|
|
|
|
var b, err = os.Open("sample.wav")
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
var player = audio.AudioContext.NewPlayer(b)
|
|
player.Play()
|
|
// Wait for the player to finish
|
|
for player.IsPlaying() {
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
err = player.Close()
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
err = b.Close()
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
}
|