package audio

import (
	"context"
	"github.com/gopxl/beep/v2"
	"github.com/gopxl/beep/v2/mp3"
	"github.com/gopxl/beep/v2/speaker"
	"github.com/gopxl/beep/v2/wav"
	"go.uber.org/zap"
	"io"
	"time"
)

var DefaultSampleRate = beep.SampleRate(44100)

func init() {
	err := speaker.Init(DefaultSampleRate, DefaultSampleRate.N(time.Second/10))
	if err != nil {
		panic("扬声器初始化异常: " + err.Error())
	}
	zap.S().Infoln("扬声器初始化完成")
}

func PlayWav(c context.Context, r io.Reader) {
	streamer, format, err := wav.Decode(r)
	if err != nil {
		return
	}
	defer streamer.Close()

	s := beep.Resample(4, format.SampleRate, DefaultSampleRate, streamer)

	ctrl := &beep.Ctrl{Streamer: s}
	done := make(chan struct{})
	speaker.Play(beep.Seq(ctrl, beep.Callback(func() {
		close(done)
	})))

	for {
		select {
		case <-done:
			return
		case <-c.Done():
			{
				speaker.Lock()
				ctrl.Streamer = nil
				speaker.Unlock()
			}
		}
	}
}

func PlayMP3(c context.Context, r io.ReadCloser) {
	streamer, format, err := mp3.Decode(r)
	if err != nil {
		return
	}
	defer streamer.Close()

	s := beep.Resample(4, format.SampleRate, DefaultSampleRate, streamer)

	ctrl := &beep.Ctrl{Streamer: s}
	done := make(chan struct{})
	speaker.Play(beep.Seq(ctrl, beep.Callback(func() {
		close(done)
	})))

	for {
		select {
		case <-done:
			return
		case <-c.Done():
			{
				speaker.Lock()
				ctrl.Streamer = nil
				speaker.Unlock()
			}
		}
	}
}
