核心变更: - 实现全局 oto.Context 单例管理(sync.Once) - 实现一次性播放:PlayWav/PlayMP3(支持 context 取消) - 实现 BGM 循环播放:PlayMP3Loop(atomic.Bool + WaitGroup) - 迁移所有业务层到新 API(TTS/BGM/待机音频) - 添加完整的单元测试(6/6 通过) 技术栈: - oto/v3 v3.3.2(低级音频播放) - hajimehoshi/go-mp3 v0.3.4(MP3 解码) - youpy/go-wav v0.3.2(WAV 解码) 移除依赖: - gopxl/beep/v2 及所有相关依赖 优化: - 流式播放,无需预先加载 - 并发安全,无竞态条件 - 资源管理清晰(defer cleanup) - Sleep 间隔优化(1ms → 10ms,降低 CPU 占用)
53 lines
1001 B
Go
53 lines
1001 B
Go
package middleware
|
|
|
|
import (
|
|
"game-driver/internal/schema"
|
|
"game-driver/leaf"
|
|
"game-driver/pkg/audio"
|
|
"game-driver/pkg/utils"
|
|
"sync"
|
|
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// PlayBgm 播放背景音乐
|
|
func PlayBgm() leaf.HandlerFunc {
|
|
return func(c *leaf.Context) {
|
|
pm := leaf.Value[*schema.PlayModal](c, PayloadJSONKey)
|
|
|
|
bgm, err := utils.LinkAudio(pm.BGM)
|
|
if err != nil {
|
|
zap.S().Errorln("背景音乐数据解析异常:", err)
|
|
}
|
|
if bgm != nil {
|
|
zap.S().Infoln("背景音乐解析成功")
|
|
var wait sync.WaitGroup
|
|
defer wait.Wait()
|
|
|
|
a := make(chan struct{})
|
|
defer close(a)
|
|
|
|
wait.Add(1)
|
|
go func() {
|
|
defer wait.Done()
|
|
|
|
zap.S().Infoln("开始播放背景音乐")
|
|
defer zap.S().Infoln("结束背景音乐播放")
|
|
|
|
_, cleanup, err := audio.PlayMP3Loop(bgm)
|
|
if err != nil {
|
|
zap.S().Errorln("播放背景音乐异常:", err)
|
|
return
|
|
}
|
|
defer cleanup()
|
|
|
|
<-a
|
|
}()
|
|
} else {
|
|
zap.S().Infoln("未解析到背景音乐")
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|