Why is replaceCurrentItem so slow on AVPlayer?

727 Views Asked by At

I'm developing a music app and I need to often swap between streaming urls. My current implementation includes an AVPlayer and a PlayerItem who are defined as global variables in my manager:

public var player: AVPlayer?
public var playerItem: AVPlayerItem?

Every time the user taps a content, I change the player item and play the new one:

public func changePlayerItem(withUrl url: URL) {
    playerItem = AVPlayerItem(url: url)
    player?.replaceCurrentItem(with: playerItem)
    ...

However the execution of the replaceCurrentItem function creates a noticeable delay of a couple of seconds. This delay is reduced to zero if I do the following instead:

 public func changePlayerItem(withUrl url: URL) {
    player = AVPlayer(url: url)
    ...

If I define playerItem as a local variable instead:

 public func changePlayerItem(withUrl url: URL) {
    let playerItem = AVPlayerItem(url: url)
    player?.replaceCurrentItem(with: playerItem)
    ...

It seems there is no delay in this case, but I hear no audio.

MacOS Big Sur 11.6, Xcode 13.1. Deployment target is iOS 13.0 and I'm testing on iPhone 7plus with iOS 15.0.2.

Why is this happening? Is there a reason behind it?

0

There are 0 best solutions below