AVPlayerItem只能分配给一个AVPlayer。将AVPlayerItem添加到AVPlayer后,将来尝试将其添加到其他AVPlayer将SIGABRT应用程序。
那么,给定AVPlayerItem,您如何确定:
以下代码可靠地演示了该问题:
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"]];
AVPlayer *firstPlayer = [[AVPlayer alloc] init];
[firstPlayer replaceCurrentItemWithPlayerItem:item];
AVPlayer *secondPlayer = [[AVPlayer alloc] init];
[secondPlayer replaceCurrentItemWithPlayerItem:item];
这是错误信息:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An AVPlayerItem cannot be associated with more than one instance of AVPlayer'
有一种半合法的方式可能在将来破裂。玩家项目有一个名为_player
的私有方法(似乎是变量)。你可以像这样查询它(技术上不使用私有API,所以我认为它应该是AppStore安全的):
id player = [item valueForKey:@"player"];
你反过来尝试过吗?尝试访问AVPlayer正在播放的项目内的详细信息
AVPlayer *firstPlayer = [[AVPlayer alloc]init];
之后你可以访问firstPlayer.currentItem
。这将让你访问firstPlayer
的AVPlayerItem
。
例如:
firstPlayer.currentItem.duration
将为您提供该赛道的持续时间。
这是一个优雅的解决方案,没有私钥和相关对象。创建自定义播放器项:
class PlayerAwareItem {
weak var player: AVPlayer?
}
设置播放器:
let item = PlayerAwareItem(asset: asset)
let player = AVPlayer(playerItem: item)
item.player = player
只要您以后拥有该项目,就可以访问该播放器(在此示例中,我们希望在停止后重新启动播放器):
@objc func handlePlayerItemDidStall(_ notification: Notification) {
guard let playerItem = notification.object as? PlayerAwareItem,
let player = playerItem.player else { return }
player.play()
}
您可以使用以下方法将AVPlayerItem
与AVPlayer
相关联:
static char playerKey;
objc_setAssociatedObject(item, &playerKey, player, OBJC_ASSOCIATION_RETAIN);
并使用:
objc_getAssociatedObject(item, &playerKey);
根据Anil的回答,对多个视频进行循环播放:
for (NSObject * obj in cachedVideos){
if ([obj isKindOfClass:[AVPlayerLayer class]]){
AVPlayerLayer * layer = (AVPlayerLayer *)obj;
if ([layer.player.currentItem isEqual:n.object]){
[layer.player seekToTime:kCMTimeZero];
[layer.player play];
break;
}
}
}