You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS 16中如何使用load(_:)方法异步加载AVAsset的时长?

替换废弃的AVAsset时长加载方法为iOS16+的load(_:)

完整替换代码(使用Async/Await)

import AVFoundation

// 封装成异步函数,方便复用
func loadVideoDuration(from path: String) async throws -> CMTime {
    let asset = AVAsset(url: URL(fileURLWithPath: path))
    // 异步加载duration属性,加载失败会直接抛出错误
    return try await asset.load(\.duration)
}

// 调用示例(需在异步上下文执行)
Task {
    do {
        let duration = try await loadVideoDuration(from: "你的视频文件路径")
        // 将CMTime转换为秒数(按需处理)
        let durationInSeconds = CMTimeGetSeconds(duration)
        print("视频时长:\(durationInSeconds)秒")
    } catch {
        // 处理各类加载错误:文件不存在、无法解析、权限问题等
        print("加载时长失败:\(error.localizedDescription)")
    }
}

关键变化说明

  • 无需手动指定keys:直接通过KeyPath \.duration明确要加载的属性,替代旧方法中手动传入["duration"]的写法
  • 错误处理更简洁:旧方法需要检查statusOfValue(forKey:error:)的返回状态,新方法通过try await结合do-catch直接捕获所有加载错误(如资源不可访问、格式不支持等)
  • 符合现代Swift异步范式:利用iOS16引入的load(_:)异步方法,配合async/await让代码逻辑更线性易读

替代闭包风格(如果仍需回调形式)

如果你的项目暂时无法完全切换到async/await,也可以将异步逻辑包装成闭包形式:

func loadVideoDuration(from path: String, completion: @escaping (Result<CMTime, Error>) -> Void) {
    let asset = AVAsset(url: URL(fileURLWithPath: path))
    Task {
        do {
            let duration = try await asset.load(\.duration)
            completion(.success(duration))
        } catch {
            completion(.failure(error))
        }
    }
}

// 调用示例
loadVideoDuration(from: "你的视频文件路径") { result in
    switch result {
    case .success(let duration):
        let seconds = CMTimeGetSeconds(duration)
        print("视频时长:\(seconds)秒")
    case .failure(let error):
        print("加载失败:\(error.localizedDescription)")
    }
}

内容的提问来源于stack exchange,提问作者YOUNG KRISS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:28:26