Reuse same AVPlayer and AVPlayerLayer or create new ones each time?
Asked Answered
S

1

9

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?

Savarin answered 29/1, 2016 at 22:44 Comment(1)
Found solution Crashlot? :PBastia
F
2

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.

Frink answered 28/9, 2018 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.