簡體   English   中英

AVPlayer 播放錯誤的視頻文件

[英]AVPlayer playing wrong video file

我遇到了一個奇怪的情況,不知道如何處理這個問題,我正在從 Firestorage 下載視頻並緩存到設備中以供將來使用,同時后台線程已經在完成它的工作,我正在將視頻 url 傳遞給 function 到播放視頻。 問題是有時 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)
    
}

任何建議將不勝感激。

this was solved because the data model which i was using to download bunch of videos files was accessed in background thread and meanwhile i was trying to assign the url to the same data model class in order to fetch the video and play in avplayer. 因此,這就是問題所在,只需將新屬性添加到數據 model 以分配 url 立即播放即可解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM