【问题标题】:AVPlayer not deallocated because of AVPlayerItem由于 AVPlayerItem,AVPlayer 未释放
【发布时间】:2021-05-22 17:01:54
【问题描述】:

我在构建视频预加载时遇到了一个问题,方法是创建(持久)AVPlayerItems 并提前将它们分配给(新/临时)AVPlayers。

我看到的第一个问题是,之前分配给AVPlayerAVPlayerItem 如果分配给新的AVPlayer 会抛出异常。后来我把它缩小到原来的 AVPlayer 没有被释放,这就是为什么 AVPlayerItem 不能与不同的播放器一起工作“一个 AVPlayerItem 不能与多个 AVPlayer 的实例相关联”。

这是最小的可重现示例:

// AVAsset can be preloaded using `asset.loadValuesAsynchronously`.
let originalAsset = AVAsset(url: URL(string: "https://www.whatever.com")!)
// AVPlayerItem is persisted across multiple AVPlayer instances.
let playerItem = AVPlayerItem(asset: originalAsset)

// Initial preload.
var player: AVPlayer? = AVPlayer(playerItem: playerItem)
player?.replaceCurrentItem(with: nil) // Doesn't help.
player = nil // Doesn't actually deinit.


// Later at some point...
player = AVPlayer(playerItem: playerItem) // Crash here.

【问题讨论】:

    标签: ios swift memory-leaks avfoundation avplayer


    【解决方案1】:

    解决方案是在需要将AVPlayer 分配给AVPlayer 时,通过创建一个新的AVPlayerItem 来确保AVPlayerItemAVPlayer 具有1:1 的关系。这是因为在AVPlayer 上设置AVPlayerItem 会在两者之间创建一个隐藏的强引用,因此持久化AVPlayerItem 会挂在AVPlayer 上,从而导致内存泄漏。

    以下是一些工作示例:

    // AVAsset can be preloaded using `asset.loadValuesAsynchronously`.
    let originalAsset = AVAsset(url: URL(string: "https://www.whatever.com")!)
    // AVPlayerItem is persisted across multiple AVPlayer instances.
    // This is not necessary if you can persist the AVAsset instead (example below).
    let playerItem = AVPlayerItem(asset: originalAsset)
    
    // Initial preload.
    var player = AVPlayer(playerItem: playerItem)
    
    
    // Later at some point...
    // Because a new `AVPlayerItem` is created, the previous one can be deallocated
    // along with the `AVPlayer` instance. 
    player = AVPlayer(playerItem: AVPlayerItem(asset: originalAsset))
    
    // Some alternatives that also work:
    player = AVPlayer(playerItem: AVPlayerItem(asset: playerItem.asset))
    player = AVPlayer(playerItem: playerItem.copy() as? AVPlayerItem)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多