核心变更: - 实现全局 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 占用)
78 lines
1.5 KiB
Go
78 lines
1.5 KiB
Go
package audio
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestPlayWav(t *testing.T) {
|
|
// 跳过测试如果没有测试文件
|
|
testFile := "testdata/test.wav"
|
|
if _, err := os.Stat(testFile); os.IsNotExist(err) {
|
|
t.Skip("测试文件不存在:", testFile)
|
|
}
|
|
|
|
f, err := os.Open(testFile)
|
|
if err != nil {
|
|
t.Fatalf("打开测试文件失败: %v", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
ctx := context.Background()
|
|
err = PlayWav(ctx, f)
|
|
if err != nil {
|
|
t.Fatalf("PlayWav 失败: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestPlayMP3(t *testing.T) {
|
|
testFile := "testdata/test.mp3"
|
|
if _, err := os.Stat(testFile); os.IsNotExist(err) {
|
|
t.Skip("测试文件不存在:", testFile)
|
|
}
|
|
|
|
f, err := os.Open(testFile)
|
|
if err != nil {
|
|
t.Fatalf("打开测试文件失败: %v", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
ctx := context.Background()
|
|
err = PlayMP3(ctx, f)
|
|
if err != nil {
|
|
t.Fatalf("PlayMP3 失败: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestPlayContextCancellation(t *testing.T) {
|
|
testFile := "testdata/test.mp3"
|
|
if _, err := os.Stat(testFile); os.IsNotExist(err) {
|
|
t.Skip("测试文件不存在:", testFile)
|
|
}
|
|
|
|
f, err := os.Open(testFile)
|
|
if err != nil {
|
|
t.Fatalf("打开测试文件失败: %v", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
// 创建一个会被快速取消的 context
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
// 启动播放后立即取消
|
|
done := make(chan error, 1)
|
|
go func() {
|
|
done <- PlayMP3(ctx, f)
|
|
}()
|
|
|
|
time.Sleep(10 * time.Millisecond)
|
|
cancel()
|
|
|
|
err = <-done
|
|
if err != context.Canceled {
|
|
t.Errorf("期望 context.Canceled 错误,得到: %v", err)
|
|
}
|
|
}
|