You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
1.4 KiB
Go
78 lines
1.4 KiB
Go
//go:build linux || darwin
|
|
// +build linux darwin
|
|
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
"github.com/gen2brain/malgo"
|
|
"github.com/youpy/go-wav"
|
|
)
|
|
|
|
func PlayWAVFile(filename string, stopPlaying *bool) error {
|
|
file, err := os.Open(filename)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
os.Exit(1)
|
|
}
|
|
defer file.Close()
|
|
|
|
w := wav.NewReader(file)
|
|
f, err := w.Format()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
reader := w
|
|
channels := uint32(f.NumChannels)
|
|
sampleRate := f.SampleRate
|
|
|
|
ctx, err := malgo.InitContext(nil, malgo.ContextConfig{}, func(message string) {
|
|
fmt.Printf("LOG <%v>\n", message)
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() {
|
|
_ = ctx.Uninit()
|
|
ctx.Free()
|
|
}()
|
|
|
|
deviceConfig := malgo.DefaultDeviceConfig(malgo.Playback)
|
|
deviceConfig.Playback.Format = malgo.FormatS16
|
|
deviceConfig.Playback.Channels = channels
|
|
deviceConfig.SampleRate = sampleRate
|
|
deviceConfig.Alsa.NoMMap = 1
|
|
|
|
// This is the function that's used for sending more data to the device for playback.
|
|
onSamples := func(pOutputSample, pInputSamples []byte, framecount uint32) {
|
|
io.ReadFull(reader, pOutputSample)
|
|
}
|
|
|
|
deviceCallbacks := malgo.DeviceCallbacks{
|
|
Data: onSamples,
|
|
}
|
|
|
|
device, err := malgo.InitDevice(ctx.Context, deviceConfig, deviceCallbacks)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer device.Uninit()
|
|
|
|
err = device.Start()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for device.IsStarted() {
|
|
if *stopPlaying {
|
|
break
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|