neekeetab / CachingPlayerItem

Play and cache media content simultaneously on your iOS device
MIT License
520 stars 89 forks source link

Caching streaming URLs (HLS) #25

Open xvicient21 opened 4 years ago

xvicient21 commented 4 years ago

I have a problem trying with streaming videos like this: https://stream.mux.com/E41fV5QQeq2zzL54A1rfXoVzw00Rmlc3B.m3u8 I can see the video is downloaded incorrectly because it's calling so fast the delegate func playerItem(_ playerItem: CachingPlayerItem, didFinishDownloadingData data: Data) and avplayer is playing nothing.

final class DemoView: UIViewController {

    var player: AVPlayer!
    var playerLayer: AVPlayerLayer!
    var playerItem: CachingPlayerItem!
    @IBOutlet weak var playerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        downloadURL()
        addPlayerAndPlay()
    }

    func addPlayerAndPlay() {
        player = AVPlayer(playerItem: playerItem)
        player.automaticallyWaitsToMinimizeStalling = false
        playerLayer = AVPlayerLayer(player: player)
        playerLayer.videoGravity = .resizeAspectFill
        playerLayer.frame = playerView.bounds
        playerView.layer.addSublayer(playerLayer)
        player.play()
    }

    func downloadURL() {
        let url = URL(string: "https://stream.mux.com/fmOV64ZNi800fgfpLa019zhnLK4whkZvz02.m3u8")!
        playerItem = CachingPlayerItem(url: url)
        playerItem.delegate = self
        playerItem.download()
    }
}

extension DemoView: CachingPlayerItemDelegate {

    func playerItem(_ playerItem: CachingPlayerItem, didFinishDownloadingData data: Data) {
        print("File is downloaded and ready for storing")
    }

    func playerItem(_ playerItem: CachingPlayerItem, didDownloadBytesSoFar bytesDownloaded: Int, outOf bytesExpected: Int) {
        print("\(bytesDownloaded)/\(bytesExpected)")
    }

    func playerItemPlaybackStalled(_ playerItem: CachingPlayerItem) {
        print("Not enough data for playback. Probably because of the poor network. Wait a bit and try to play later.")
    }

    func playerItem(_ playerItem: CachingPlayerItem, downloadingFailedWith error: Error) {
        print(error)
    }

}

Any idea why it's not working with HLS videos?

JoeyBodnar commented 4 years ago

Anyone ever figure this out?