package audio

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

func PlayBgmMP3(r io.ReadCloser, opts ...beep.LoopOption) (*beep.Ctrl, func() error, error) {
	streamer, format, err := mp3.Decode(r)
	if err != nil {
		return nil, func() error { return nil }, err
	}

	loop2, err := beep.Loop2(streamer, opts...)
	if err != nil {
		zap.S().Infoln("循环播放异常: ", err)
		return nil, streamer.Close, err
	}

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

	ctrl := &beep.Ctrl{Streamer: s}
	speaker.Play(beep.Seq(ctrl, beep.Callback(func() {
		streamer.Close()
	})))

	return ctrl, streamer.Close, nil
}
