Update callback function signatures to use the any alias introduced in Go 1.18, improving code readability and following current Go conventions. Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
75 lines
1.7 KiB
Go
75 lines
1.7 KiB
Go
package video
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
libvlc "github.com/adrg/libvlc-go/v3"
|
|
)
|
|
|
|
func Play(ctx context.Context, path string, local bool) error {
|
|
// 1. 初始化 VLC
|
|
if err := libvlc.Init("--no-xlib"); err != nil {
|
|
return fmt.Errorf("VLC初始化失败: %w", err)
|
|
}
|
|
defer libvlc.Release()
|
|
|
|
// 2. 创建播放器
|
|
player, err := libvlc.NewPlayer()
|
|
if err != nil {
|
|
return fmt.Errorf("播放器创建失败: %w", err)
|
|
}
|
|
defer player.Stop()
|
|
defer player.Release()
|
|
|
|
// 3. 注册结束事件
|
|
eventManager, err := player.EventManager()
|
|
if err != nil {
|
|
return fmt.Errorf("事件管理器获取失败: %w", err)
|
|
}
|
|
|
|
done := make(chan struct{})
|
|
defer close(done)
|
|
|
|
_, err = eventManager.Attach(libvlc.MediaPlayerEndReached, func(libvlc.Event, any) {
|
|
done <- struct{}{}
|
|
}, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("事件绑定失败: %w", err)
|
|
}
|
|
|
|
// 4. 加载并播放文件
|
|
if local {
|
|
if _, err := player.LoadMediaFromPath(path); err != nil {
|
|
return fmt.Errorf("文件加载失败: %w", err)
|
|
}
|
|
} else {
|
|
if _, err := player.LoadMediaFromURL(path); err != nil {
|
|
return fmt.Errorf("文件加载失败: %w", err)
|
|
}
|
|
}
|
|
|
|
if err := player.Play(); err != nil {
|
|
return fmt.Errorf("播放启动失败: %w", err)
|
|
}
|
|
|
|
// 设置全屏模式
|
|
if err := player.SetFullScreen(true); err != nil {
|
|
return fmt.Errorf("设置全屏模式失败: %w", err)
|
|
}
|
|
|
|
// 设置音量为最大
|
|
if err := player.SetVolume(100); err != nil {
|
|
return fmt.Errorf("设置音量失败: %w", err)
|
|
}
|
|
|
|
// 5. 等待事件
|
|
fmt.Printf("正在播放: %s\n", path)
|
|
select {
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("播放被用户中断")
|
|
case <-done:
|
|
fmt.Println("播放正常结束")
|
|
return nil
|
|
}
|
|
}
|