Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 971
Crashalot Avatar asked Jan 29 '16 22:01

Crashalot


1 Answers

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.

like image 101
rorschach Avatar answered Sep 20 '22 21:09

rorschach