我有UIView
,其中包含一些文字和观点。在每个视图中,我需要使用AVPlayer
播放视频,但我的问题只是第一个视图显示视频:
这是我的代码:
func playVideo(name:String , onView:UIView) {
let path = Bundle.main.path(forResource: name, ofType: "mp4")
let videoURL = URL(fileURLWithPath: path!)
let player = AVPlayer(url: videoURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = onView.frame
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
onView.layer.addSublayer(playerLayer)
player.play()
}
使用该功能:
override func viewDidLoad() {
super.viewDidLoad()
//ScrollView
scrollView.contentSize = menuView.frame.size
scrollView.addSubview(menuView)
//Play videos
playVideo(name: "pizza", onView: videoView1)
playVideo(name: "salad", onView: videoView2)
playVideo(name: "fries", onView: videoView3)
}
当我运行应用视频时只能在videoView1
播放,有什么建议为什么会这样?
我还将代码放在viewWillAppear
,viewDidLayoutSubviews
答案 0 :(得分:3)
根据 Apple doc :
类AVPlayer
注意强>
AVPlayer旨在一次播放单个媒体资产。
答案 1 :(得分:0)
我刚刚找到了替代解决方案,我将package main
import (
"context"
"fmt"
"time"
)
func main() {
forever := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
go func(ctx context.Context) {
for {
select {
case <-ctx.Done(): // if cancel() execute
forever <- struct{}{}
return
default:
fmt.Println("for loop")
}
time.Sleep(500 * time.Millisecond)
}
}(ctx)
go func() {
time.Sleep(3 * time.Second)
cancel()
}()
<-forever
fmt.Println("finish")
}
替换为UIView
,然后将其与UIContainerView
链接到其他视图控制器,并在每个视图控制器中播放视频。现在它完全符合我的预期。