我正在尝试流式传输m3u8网址并保存离线状态。 然后从离线播放。 我正在使用Apple HTTP Live Streaming
使用以下代码
开始下载func setupAssetDownload() {
// Create new background session configuration.
configuration = URLSessionConfiguration.background(withIdentifier: DOWNLOAD_ID)
// Create a new AVAssetDownloadURLSession with background configuration, delegate, and queue
downloadSession = AVAssetDownloadURLSession(configuration: configuration,
assetDownloadDelegate: self,
delegateQueue: OperationQueue.main)
let url = URL(string: urlString)
let asset = AVURLAsset(url: url!)
// Create new AVAssetDownloadTask for the desired asset
let downloadTask = downloadSession.makeAssetDownloadTask(asset: asset, assetTitle: "asset_Title", assetArtworkData: nil, options: nil)
// Start task and begin download
downloadTask?.resume()
}
其中,
let DOWNLOAD_ID = "downloadIdentifier"
let urlString = "http://domain/vod/mp4:sample1.mp4/playlist.m3u8"
// Saving the Download Location
func urlSession(_ session: URLSession, assetDownloadTask: AVAssetDownloadTask, didFinishDownloadingTo location: URL) {
print("didFinishDownloadingTo \(location.relativePath)")
// Do not move the asset from the download location
UserDefaults.standard.set(location.relativePath, forKey: "assetPath")
}
尝试离线时, 我可以获得AVURLAsset,
<AVURLAsset: 0x1742319e0, URL = file:///var/mobile/Containers/Data/Application/79C0043F-6161-4231-9129-B71C95903E05/Library/com.apple.UserManagedAssets.bhVNRN/asset_Title_63128673BE57FBDD.movpkg/>
但是,不要从资产中支付。
func playOfflineAsset() {
guard let assetPath = UserDefaults.standard.value(forKey: "assetPath") as? String else {
// Present Error: No offline version of this asset available
return
}
let baseURL = URL(fileURLWithPath: NSHomeDirectory())
let assetURL = baseURL.appendingPathComponent(assetPath)
let asset = AVURLAsset(url: assetURL)
let player = AVPlayer(url:assetURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = videoView2.bounds
playerLayer.backgroundColor = UIColor.purple.cgColor
videoView2.layer.addSublayer(playerLayer)
player.play()
if let cache = asset.assetCache, cache.isPlayableOffline {
// Set up player item and player and begin playback
print("exist")
} else {
// Present Error: No playable version of this asset exists offline
print("doesn't exist")
}
}
答案 0 :(得分:0)
你需要添加AVPlayerController到AVPlayer可以播放声音,我不知道为什么,但它的工作对我来说
//设置播放器项目和播放器并开始播放
let playerItem = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: playerItem)
// play without present playerController
self.player?.play()
// play with present playerController
// let playerController = AVPlayerViewController()
// playerController.player = player
// self.present(playerController, animated: true) {
// self.player?.play()
// }
编辑:确保hls不加密。