![](/img/trans.png)
[英]An AVPlayerItem cannot be associated with more than one instance of AVPlayer'
[英]Find the AVPlayer associated with an AVPlayerItem
一个 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;
}
}
}
如果您要将项目分配给第二个玩家,那么在分配之前您必须将第一个玩家的项目设置为nil并在分配给第二个玩家之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.