【问题标题】:AVPlayer playing wrong video fileAVPlayer 播放错误的视频文件
【发布时间】:2022-01-07 12:27:23
【问题描述】:

我遇到了一个奇怪的情况,不知道如何处理这个问题,我正在从 firestorage 下载视频并缓存到设备中以供将来使用,同时后台线程已经在完成它的工作,我正在将视频 url 传递给播放视频的功能。问题是有时 avplayer 正在播放正确的视频,有时会从缓存中获取其他视频 url。

您可以在下面找到代码:

  func cacheVideo(for exercise: Exercise) {
    print(exercise.imageFileName)
    guard let filePath = filePathURL(for: exercise.imageFileName) else { return }
    if fileManager.fileExists(atPath: filePath.path) {
        //  print("already exists")
    } else {
        exercise.loadRealURL {  (url) in
            print(url)
            self.getFileWith(with: url, saveTo: filePath)
        }
    }
}

在此处写入文件

    func getFileWith(with url: URL, saveTo saveFilePathURL: URL) {
    
    DispatchQueue.global(qos: .background).async {
        
        print(saveFilePathURL.path)
        if let videoData = NSData(contentsOf: url) {
            videoData.write(to: saveFilePathURL, atomically: true)
            DispatchQueue.main.async {
                // print("downloaded")
            }
        } else {
            DispatchQueue.main.async {
                let error = NSError(domain: "SomeErrorDomain", code: -2001 /* some error code */, userInfo: ["description": "Can't download video"])
                print(error.debugDescription)
                
            }
        }
    }
}

现在使用这个播放视频

func startPlayingVideoOnDemand(url : URL) {
    
    activityIndicatorView.startAnimating()
    activityIndicatorView.isHidden = false
    print(url)
    let cachingPlayerItem = CachingPlayerItem(url: url)
    
    cachingPlayerItem.delegate = self
    cachingPlayerItem.download()
    // cachingPlayerItem.preferredPeakBitRate = 0
    let avasset = AVAsset(url: url)
    let playerItem = AVPlayerItem(asset: avasset)
    let player = AVPlayer(playerItem: playerItem)
    player.automaticallyWaitsToMinimizeStalling = false
    initializeVideoLayer(for: player)
    
}

任何建议都将受到高度赞赏。

【问题讨论】:

  • 我已经解决了,谢谢

标签: ios swift caching avfoundation avplayer


【解决方案1】:

这已解决,因为我用来下载大量视频文件的数据模型是在后台线程中访问的,同时我试图将 url 分配给相同的数据模型类以获取视频并在 avplayer 中播放.因此,这就是问题所在,只需在数据模型中添加一个新属性以分配要立即播放的 url 即可解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多