Associate AVPlayerItem with new AVPlayer in Swift?
Asked Answered
A

1

5

How can I reassociate an instance of AVPlayerItem with a new AVPlayer in Swift? When used in an initializer. Every time I try to reassign an AVPlayerItem to a different AVPlayer even after I've set all references to the AVPlayer to nil (so it should get garbage collected), it complains that an AVPlayerItem cannot be assigned to more than 1 AVPlayer object. I understand a few ways to get around it but I want to know why this way doesn't work.

let player: AVPlayer = AVPlayer(playerItem: somePlayerItem)

I don't know what happens during this declaration but something somewhere gets set to allow somePlayerItem know it has an associated player. Does this have some observer set somewhere or property set that would note this?

Does anyone know a way to reassign this AVPlayerItem to a different AVPlayer after the original AVPlayer's references have been destroyed? I know I can just make a new AVPlayerItem using the URL but I want to know if I can keep the same object.

Anthropopathy answered 5/11, 2015 at 4:13 Comment(6)
Have you tried to replace the current item using: replaceCurrentItemWithPlayerItem: ? And why do you need to use an item with another player anyway?Granulate
That would work. It just seems odd that a declared AVPlayerItem is a one-time-use. Why wouldn't you just be able to store a video in a AVPlayerItem and display it in different AVPlayers?Anthropopathy
AVPlayerItem does not store a video, it references an AVAsset, so it should be pretty light-weight wrapper around it.Granulate
So it did help to store the AVAsset as opposed to storing the the AVPlayerItem. I just want to know if there is any way to change the associated player for that AVPlayerItem.Anthropopathy
[oldPlayer replaceCurrentItemWithPlayerItem:nil];Granulate
AVPlayer* anotherPlayer = [AVPlayer playerWithPlayerItem:yourItem];Granulate
C
8

You can't reuse an item, but you can reuse an asset.

So create your asset once:

let asset=AVAsset(URL: your_url)

Then reuse it when needed by creating a new item:

let item=AVPlayerItem(asset: asset)
let player=AVPlayer(playerItem: item)
Carlita answered 21/6, 2016 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.