feat(audio): 使用 oto/v3 重构音频播放系统,移除 beep/v2 依赖
核心变更: - 实现全局 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 占用)
This commit is contained in:
64
pkg/audio/loop.go
Normal file
64
pkg/audio/loop.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/ebitengine/oto/v3"
|
||||
"github.com/hajimehoshi/go-mp3"
|
||||
)
|
||||
|
||||
// PlayMP3Loop 循环播放 MP3(非阻塞)
|
||||
// 返回 player 和清理函数,调用者负责 defer cleanup()
|
||||
func PlayMP3Loop(r io.ReadCloser) (*oto.Player, func() error, error) {
|
||||
otoCtx, err := initContext()
|
||||
if err != nil {
|
||||
r.Close()
|
||||
return nil, func() error { return nil }, err
|
||||
}
|
||||
|
||||
// Read the entire MP3 into memory for seeking support
|
||||
data, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
r.Close()
|
||||
return nil, func() error { return nil }, err
|
||||
}
|
||||
r.Close()
|
||||
|
||||
dec, err := mp3.NewDecoder(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, func() error { return nil }, err
|
||||
}
|
||||
|
||||
player := otoCtx.NewPlayer(dec)
|
||||
|
||||
playing := atomic.Bool{}
|
||||
playing.Store(true)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for playing.Load() {
|
||||
player.Play()
|
||||
for playing.Load() && player.IsPlaying() {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if playing.Load() {
|
||||
_, _ = dec.Seek(0, io.SeekStart)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
cleanup := func() error {
|
||||
playing.Store(false)
|
||||
wg.Wait()
|
||||
player.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
return player, cleanup, nil
|
||||
}
|
||||
Reference in New Issue
Block a user