首页 > 解决方案 > 获取 naturalSize 和列表分辨率视频 m3u8

问题描述

我播放视频 m3u8。

我尝试使用let videoAssetSource = AVAsset(url: videoURL)videoAssetSource.tracks(withMediaType: .video).count总是返回 0。当我使用链接 mp4 时,这是成功的。

如何在播放视频时获得列表质量链接 m3u8 支持并更改质量。

标签: iosswifthttp-live-streaming

解决方案


您必须为分辨率创建自己的相应模型,但这样的代码应该可以工作。

    /// Downloads the stream file and converts it to the raw playlist.
    /// - Parameter completion: In successful case should return the `RawPlalist` which contains the url with which was the request performed
    /// and the string representation of the downloaded file as `content: String` parameter.
    func getPlaylist(from url: URL, completion: @escaping (Result<RawPlaylist, Error>) -> Void) {
        task = URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                completion(.failure(error))
            } else if let data = data, let string = String(data: data, encoding: .utf8) {
                completion(.success(RawPlaylist(url: url, content: string)))
            } else {
                completion(.failure(PlayerException.MEDIA_ERR_DECODE)) // Probably an MP4 file.
            }
        }
        task?.resume()
    }

    /// Iterates over the provided playlist contetn and fetches all the stream info data under the `#EXT-X-STREAM-INF"` key.
    /// - Parameter playlist: Playlist object obtained from the stream url.
    /// - Returns: All available stream resolutions for respective bandwidth.
    func getStreamResolutions(from playlist: RawPlaylist) -> [StreamResolution] {
        var resolutions = [StreamResolution]()
        playlist.content.enumerateLines { line, shouldStop in
            let infoline = line.replacingOccurrences(of: "#EXT-X-STREAM-INF", with: "")
            let infoItems = infoline.components(separatedBy: ",")
            let bandwidthItem = infoItems.first(where: { $0.contains(":BANDWIDTH") })
            let resolutionItem = infoItems.first(where: { $0.contains("RESOLUTION")})
            if let bandwidth = bandwidthItem?.components(separatedBy: "=").last,
               let numericBandwidth = Double(bandwidth),
               let resolution = resolutionItem?.components(separatedBy: "=").last?.components(separatedBy: "x"),
               let strignWidth = resolution.first,
               let stringHeight = resolution.last,
               let width = Double(strignWidth),
               let height = Double(stringHeight) {
                resolutions.append(StreamResolution(maxBandwidth: numericBandwidth,
                                                    averageBandwidth: numericBandwidth,
                                                    resolution: CGSize(width: width, height: height)))
            }
        }
        return resolutions
    }
}


推荐阅读