无法上网时无法播放下载的HLS内容

问题描述 投票:0回答:1

我正在下载和播放HLS内容,我正在使用以下代码下载HLS

func downloadTask() {

let videoUrl =  URL(string: "https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8")!

    configuration = URLSessionConfiguration.background(withIdentifier: downloadIdentifier)
    downloadSession = AVAssetDownloadURLSession(configuration: configuration!, assetDownloadDelegate: self, delegateQueue: OperationQueue.main)

    let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    destinationUrl = documentsDirectoryURL.appendingPathComponent(videoUrl.lastPathComponent)


    var urlComponents = URLComponents(
        url: videoUrl,
        resolvingAgainstBaseURL: false
        )!
    urlComponents.scheme = "https"
    do {
        let asset = try AVURLAsset(url: urlComponents.url!)
        asset.resourceLoader.setDelegate(self, queue: DispatchQueue(label: "com.example.AssetResourceLoaderDelegateQueue"))

        if #available(iOS 10.0, *) {
            assetDownloadTask = downloadSession!
                .makeAssetDownloadTask(
                    asset: asset,
                    assetTitle: "RG-TVVideo",
                    assetArtworkData: nil,
                    options: nil
            )
            APP_DELEGATE.isProgressRunning = true
            assetDownloadTask?.resume()
        } else {
            // Fallback on earlier versions
        }
    } catch { print("Erorr while parsing the URL.") }
}

下载完成

 func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {

    if #available(iOS 11.0, *) {
        let storageManager = AVAssetDownloadStorageManager.shared()
        let newPolicy = AVMutableAssetDownloadStorageManagementPolicy()
        newPolicy.expirationDate = Date()
        newPolicy.priority = .important
        let baseURL = URL(fileURLWithPath: NSHomeDirectory())
        let assetURL = baseURL.appendingPathComponent(location.relativePath)
        storageManager.setStorageManagementPolicy(newPolicy, for: assetURL)

        UserDefaults.standard.set(location.relativePath, forKey: "videoPath")
        strDownloadStatus = "5"
        let dictVideoInfo = ["strDownloadStatus" : "5","VideoID":self.strID]

// Here I am Storing Downloaded location in to database 
            DBManager.shared.updateVideoStatus(strVideoID: APP_DELEGATE.arrTempVideoIds.object(at: 0) as! String, strStatus: "5", strSavePath: location.relativePath) { (status) in }

        DispatchQueue.main.async {
            NotificationCenter.default.post(name: NSNotification.Name.init("UpdateProgress"), object: self.percentageComplete, userInfo: dictVideoInfo)
        }

    }
}

现在,我正在尝试从存储在数据库中的位置获取视频路径,并尝试使用以下代码脱机播放(不使用互联网)

  func setLocalPlayer(strDownloadPath: String) {

    let strDownloadPath = “”

    //Getting path from database
    DBManager.shared.getDownloadedPath(videoID:  VideoID) { (strPath) in
        strDownloadPath = strPath
    }

    activityIndicator.isHidden = false

    let baseURL = URL(fileURLWithPath: NSHomeDirectory())
    let assetURL = baseURL.appendingPathComponent(strDownloadPath)
    let asset = AVURLAsset(url: assetURL)

    //        if let cache = asset.assetCache, cache.isPlayableOffline {
    //            let videoAsset = AVURLAsset(url: assetURL)
    asset.resourceLoader.preloadsEligibleContentKeys = true

    asset.resourceLoader.setDelegate(self, queue: DispatchQueue(label: "com.example.AssetResourceLoaderDelegateQueue"))
    let playerItem = AVPlayerItem(asset: asset)
    avPlayer = AVPlayer(playerItem: playerItem)
    avPlayerLayer = AVPlayerLayer()
    avPlayerLayer.frame = CGRect(x: 0, y: 0, width: playerContainer.frame.width, height: playerContainer.frame.height)
    avPlayerLayer.videoGravity = .resize

    avPlayerLayer.player = avPlayer

    playerContainer.layer.addSublayer(avPlayerLayer)

    let interval = CMTime(seconds: 0.01, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
    timeObserver = avPlayer?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { elapsedTime in
        self.updateVideoPlayerState()

        if self.avPlayer != nil {
            self.bufferState()
        }
    })

    self.slider.setThumbImage(UIImage(named: "slider_dot"), for: UIControl.State.normal)
    resetTimer()

    avPlayer.play()
    isPlaying = true
    //        }
}

NOTE:启用互联网后,此代码可以正常工作>>

我已经引用了以下链接

https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/MediaPlaybackGuide/Contents/Resources/en.lproj/HTTPLiveStreaming/HTTPLiveStreaming.html

https://assist-software.net/snippets/how-play-encrypted-http-live-streams-offline-avfoundation-ios-using-swift-4

Downloading and playing offline HLS Content - iOS 10

请指导我在做什么错。

谢谢

我正在下载和播放HLS内容,要下载HLS,我正在使用以下代码func downloadTask(){让videoUrl = URL(string:“ https://bitdash-a.akamaihd.net/content/。 。

swift avplayer offline http-live-streaming playback
1个回答
0
投票

嗯,我不知道这是否是您的错误,但请继续阅读:

© www.soinside.com 2019 - 2024. All rights reserved.