If you need to play multiple videos in the same view, there are seemingly two approaches: (1) create new AVPlayerLayers and AVPlayers each time; or (2) reuse the same ones.
Assume your class is designed to play multiple videos, and the following code is used to load a new video:
var player = AVPlayer()
var playerItem:AVPlayerItem?
var playerLayer:AVPlayerLayer?
// Get file path to <videoURL>
videoURL = getFilePath(videoURL)
// Create player & layer
playerItem = AVPlayerItem(URL: NSURL(fileURLWithPath: videoURL))
player = AVPlayer(playerItem: playerItem!)
playerLayer = AVPlayerLayer(player: player)
The second option, after creating a AVPlayerLayer and AVPlayer, is to reuse them. So you could replace the last two lines with this:
player.replaceCurrentItemWithPlayerItem(playerItem!)
What are the pros/cons of each option? Is it okay to use option 1, or is that considered wasteful?
If you are trying to play multiple videos at the same time you would need to create multiple AVPlayers with corresponding AVPlayerLayers.
But if you are switching between multiple videos through a tap gesture or a swipe gesture you could recycle two AVPlayers. One for playing the current video and the other for preloading the next.
Alternatively you could also stick to just one AVQueuePlayer and one AVPlayerLayer and queue up your items. AVQueuePlayer automatically preloads the next item in the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With