可以缓存HLS CMAF格式视频,原理如下:
- 用户将反向代理URL设置到
AVPlayer
而不是原始URL。- https://example.com/vod.m3u8 + http://127.0.0.1:8080/vod.m3u8?__hls_origin_url=https://example.com/vod.m3u8
- AVPlayer请求一个播放列表((
.m3u8
))到本地的反向代理服务器。 - 反向代理服务器获取原始播放列表,并将所有URI替换为指向本机地址。
#EXTM3U #EXTINF:12.000, - vod_00001.ts + http://127.0.0.1:8080/vod.m3u8?__hls_origin_url=https://example.com/vod_00001.ts #EXTINF:12.000, - vod_00002.ts + http://127.0.0.1:8080/vod.m3u8?__hls_origin_url=https://example.com/vod_00002.ts #EXTINF:12.000, - vod_00003.ts + http://127.0.0.1:8080/vod.m3u8?__hls_origin_url=https://example.com/vod_00003.ts
- AVPlayer请求段(
.ts
)到本地的反向代理服务器。 - 反向代理服务器获取原始段并缓存它。下次服务器将返回相同段的缓存数据。
appdelegate
CMAFHLSCachingReverseProxyServer.setUp()
CMAFHLSCachingReverseProxyServer.sharedInstance?.start()
vc
let reverseProxyURL = CMAFHLSCachingReverseProxyServer.sharedInstance?.reverseProxyURL(from: playlistURL)! ?? URL(string: "www.apple.com")
let playerItem = AVPlayerItem(url: reverseProxyURL!)
player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = view.bounds // 将视频画面填充到特定的UIView中
view.layer.addSublayer(playerLayer)
player.currentItem?.preferredForwardBufferDuration = 1
player.play()
cmafhlscache通过CocoaPods提供。要安装它,只需将以下行添加到您的Podfile中
pod 'cmafhlscache', :git => "https://github.com/yelunnibi/cmafhlscache.git", :branch => 'main'
cmafhlscache在MIT许可证下可用。有关更多信息,请参阅LICENSE文件。