2024-08-04 23:05:23 -04:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
2024-08-04 23:42:13 -04:00
|
|
|
"dynatron.me/x/stillbox/internal/minimp3"
|
2024-08-04 23:32:46 -04:00
|
|
|
"github.com/hajimehoshi/oto"
|
2024-08-04 23:05:23 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type Player struct {
|
2024-08-04 23:50:14 -04:00
|
|
|
ctx *oto.Context
|
|
|
|
sampleRate int
|
|
|
|
channels int
|
2024-08-04 23:05:23 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewPlayer() *Player {
|
|
|
|
p := &Player{}
|
|
|
|
|
|
|
|
return p
|
|
|
|
}
|
|
|
|
|
2024-08-04 23:32:46 -04:00
|
|
|
func (p *Player) initOto(samp, channels int) error {
|
2024-08-04 23:50:14 -04:00
|
|
|
if samp != p.sampleRate || channels != p.channels {
|
|
|
|
if p.ctx != nil {
|
|
|
|
err := p.ctx.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
if p.ctx, err = oto.NewContext(samp, channels, 2, 1024); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-08-04 23:32:46 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2024-08-04 23:05:23 -04:00
|
|
|
}
|
|
|
|
|
2024-08-04 23:32:46 -04:00
|
|
|
func (p *Player) playMP3(audio []byte) error {
|
|
|
|
var dec *minimp3.Decoder
|
|
|
|
var data []byte
|
2024-08-04 23:05:23 -04:00
|
|
|
var err error
|
2024-08-04 23:32:46 -04:00
|
|
|
if dec, data, err = minimp3.DecodeFull(audio); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
err = p.initOto(dec.SampleRate, dec.Channels)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var player = p.ctx.NewPlayer()
|
|
|
|
player.Write(data)
|
|
|
|
|
|
|
|
<-time.After(time.Second)
|
|
|
|
|
|
|
|
dec.Close()
|
|
|
|
if err = player.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Player) Play(audio []byte, mimeType string) error {
|
2024-08-04 23:05:23 -04:00
|
|
|
switch mimeType {
|
|
|
|
case "audio/mpeg":
|
2024-08-04 23:32:46 -04:00
|
|
|
return p.playMP3(audio)
|
2024-08-04 23:05:23 -04:00
|
|
|
case "audio/wav":
|
2024-08-04 23:50:14 -04:00
|
|
|
panic("wav not implemented yet")
|
2024-08-04 23:05:23 -04:00
|
|
|
default:
|
|
|
|
return fmt.Errorf("unknown format %s", mimeType)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|