iOS 下载和播放 M3U8

8,182 阅读3分钟

WLM3U 是一个用 Swift 实现的 M3U 工具。

项目地址 github.com/WillieWangW…

示例

clone 这个仓库,接着执行 pod install 命令,然后运行示例项目。

要求

iOS Swift
9.0 + 5.0 +

安装

WLM3U 可通过 CocoaPods 安装,只需将以下行添加到 Podfile 即可

pod 'WLM3U'

使用

解析 M3U 文件

let url = URL(string:"http://xxx.com/yyy.m3u8")! // M3U 文件的 URL
let size: Int = <#fileSize#>                     // 所有 ts 文件的总大小

WLM3U
    .attach(url: url, size: size, completion: { (result) in
        switch result {
        case .success(let model):
            model.name  // yyy
            model.tsArr // ts 文件数组
            ...
        case .failure(let error):
            print("attach failure " + error.localizedDescription)
        }
    })

下载 M3U 文件描述的 ts 文件

let url = URL(string:"http://xxx.com/yyy.m3u8")! // M3U 文件的 URL
let size: Int = <#fileSize#>                     // 所有 ts 文件的总大小

WLM3U
    .attach(url: url, size: size)
    .download(progress: { (progress, completedCount) in
        progress       // 当前下载的进度
        completedCount // 下载速度( B/S )
        
    }, completion: { (result) in
        switch result {
        case .success(let url):
            url // ts 文件所在的目录
        case .failure(let error):
            print("download failure " + error.localizedDescription)
        }
    })

将下载的 ts 文件合并成一个文件

let url = URL(string:"http://xxx.com/yyy.m3u8")! // M3U 文件的 URL
let size: Int = <#fileSize#>                     // 所有 ts 文件的总大小

WLM3U
    .attach(url: url, size: size)
    .download()
    .combine(completion: { (result) in
        switch result {
        case .success(let url):
            url // 合并完成后文件所在的目录
        case .failure(let error):
            print("combine failure " + error.localizedDescription)
        }
    })

自动获取 ts 文件总大小

WLM3U 支持自动获取所有文件的总大小,只需设置 calculateSize 参数即可:

let url = URL(string:"http://xxx.com/yyy.m3u8")! // M3U 文件的 URL

WLM3U
    .attach(url: url, calculateSize: true)
    .download()
    .combine()

获取大小的过程是异步的,可以通过接收 TaskGetFileSizeProgressNotificationTaskGetFileSizeCompletionNotification 来获取大小数据。

暂停与恢复任务

为了简化接口,WLM3U 没有 暂停恢复 的概念,它们和 取消添加 是一样的,所以:

需要暂停一个任务时,调用 cancel(url: URL)

需要取消一个任务时,调用 cancel(url: URL),并通过 folder(for url: URL) 获取到此任务缓存目录,并删除它即可。

需要添加一个任务时,调用 attach(url: URL)

需要恢复一个任务时,调用 attach(url: URL),如果本地存在之前的缓存,会自动继续下载剩余的文件。

监听状态

WLM3U 内置了几个状态的通知,你可以接收这些通知来处理数据:

/// 下载进度发生变化时会发出的通知。
public let TaskProgressNotification: Notification.Name

/// 获取文件总大小的进度发生变化时会发出的通知。
public let TaskGetFileSizeProgressNotification: Notification.Name

/// 获取文件总大小完成时会发出的通知。
public let TaskGetFileSizeCompletionNotification: Notification.Name

/// 任务完成时会发出的通知。
public let TaskCompletionNotification: Notification.Name

/// 任务发生错误时会发出的通知。
public let TaskErrorNotification: Notification.Name

播放下载的文件

AVPlayer 与 WLM3U 暂不支持播放本地 ts 文件,这里提供两个简单可行的替代方案。

使用 GCDWebServer 搭建本地服务

引入 GCDWebServer 库:

pod "GCDWebServer"

创建本地 HTTP 服务来提供下载好的 ts 文件:

let server = GCDWebServer()
let path = <#folderPath#> // ts 文件所在的本地目录
server.addGETHandler(forBasePath: "/",
                     directoryPath: path,
                     indexFilename: "file.m3u8",
                     cacheAge: 3600,
                     allowRangeRequests: true)
server.start()

使用 AVPlayer 来播放本地服务提供的 ts 文件:

let url = URL(string: "http://localhost:\(server.port)/file.m3u8")
let player = AVPlayer(url: url)

使用 FFmpeg 将 ts 文件转码成 mp4 文件

引入 mobile-ffmpeg-full 库:

pod "mobile-ffmpeg-full"

执行转码命令:

let command = "-i 'ts文件所在的路径' 'mp4文件要保存到的路径'"

let result = MobileFFmpeg.execute(command)

if result == RETURN_CODE_SUCCESS {
    // 转码完成
}

接下来直接播放转码得到的 mp4 文件即可。

作者

Willie, willie.wangwei@gmail.com