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) } }