DookieMan
DookieMan

Reputation: 1044

AVPlayer won't play new AVPlayerItem after failure occurs

I'm working on a App that plays audio files or streams and came across an issue I can't resolve. Essentially my AVPlayer no longer plays new items after a failure occurs for the current item. Below is a quick App you can copy/paste to reproduce.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    @objc var player: AVPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.player = AVPlayer.init(playerItem: AVPlayerItem.init(url: URL.init(string: "file:///Users/bobsacamano/Library/Developer/CoreSimulator/Devices/AD4CC461-847E-441B-98BA-D5A62EE210AE/data/Containers/Data/Application/F3AEA610-5358-4EAD-93B3-F30E9491D052/Library/07E2837C-5FF2-4B30-99A7-CCE683C19C29.mp3")!))
        self.player.play()
        self.addObserver(self, forKeyPath: #keyPath(player.currentItem.status), options: .new, context: nil)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

     override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == #keyPath(player.currentItem.status) {
            switch player.currentItem!.status {
            case .readyToPlay:
                print("Ready to play")
            case .failed:
                print("Failure \(String(describing: player.currentItem!.error?.localizedDescription))")
                self.player.replaceCurrentItem(with: AVPlayerItem.init(url: URL.init(string: "http://traffic.libsyn.com/atpfm/atp281.mp3")!))
                self.player.play()
            case .unknown:
                print("Unknown")
            }
        }
    }
}

The initial AVPlayerItem doesn't exist, so KVO will return a failure. If I try and replace the item with a working URL, it still fails to play. Am I missing something obvious?

Upvotes: 1

Views: 3116

Answers (1)

NormanOu
NormanOu

Reputation: 75

https://developer.apple.com/documentation/avfoundation/avplayer/1388096-status the document says that "When the value of this property is AVPlayer.Status.failed, you can no longer use the player for playback and you need to create a new instance to replace it."

Upvotes: 5

Related Questions