iOS.Lover
iOS.Lover

Reputation: 6051

Play several videos using AVPlayer in a view

I have an UIView which contains some some texts and views. in each view I need to play a video with AVPlayer , but my problem is only the first view shows the video :

enter image description here

Here is my code :

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

}

Using the function :

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

when I run the app video only play in videoView1 , any suggestion why this happens ? I also put my code in viewWillAppear , viewDidLayoutSubviews

Upvotes: 0

Views: 1120

Answers (2)

iOS.Lover
iOS.Lover

Reputation: 6051

I just found an alternative solution , I replaced UIView with UIContainerView and then link them with Embed to other view controller and play video in each view controller. Now it works perfectly as I expected.

enter image description here

Upvotes: 1

Francesco Deliro
Francesco Deliro

Reputation: 3939

According to Apple doc:

class AVPlayer

Note

AVPlayer is intended for playing a single media asset at a time.

Upvotes: 3

Related Questions