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

iOS中用Swift检测视频容器是否为.mp4或.mov(非扩展名判断)

基于媒体内容判断视频容器与编码格式的实现方案

完全可以通过AVAsset获取视频的真实容器和编码格式,这是iOS上最可靠的原生方案,不受文件扩展名修改的影响。此外也有其他可选方式,下面详细说明:

一、用AVAsset解析真实格式信息

AVFoundation的AVAsset类会直接解析媒体文件的底层数据,能准确拿到容器类型和编码格式。实现时注意异步加载属性,避免阻塞主线程:

示例代码

import AVFoundation

func analyzeVideoFormat(from url: URL) {
    let asset = AVAsset(url: url)
    
    // 异步加载关键属性:tracks(轨道信息)和fileType(容器类型)
    asset.loadValuesAsynchronously(forKeys: ["tracks", "fileType"]) {
        DispatchQueue.main.async {
            // 获取容器格式
            var fileTypeError: NSError?
            if asset.statusOfValue(forKey: "fileType", error: &fileTypeError) == .loaded {
                guard let fileType = asset.fileType else {
                    print("无法识别容器格式")
                    return
                }
                
                switch fileType {
                case .mp4:
                    print("真实容器格式:MP4")
                case .mov:
                    print("真实容器格式:MOV")
                default:
                    print("非目标容器格式:\(fileType.rawValue)")
                }
            } else {
                print("获取容器格式失败:\(fileTypeError?.localizedDescription ?? "未知错误")")
            }
            
            // 获取视频编码格式
            var tracksError: NSError?
            if asset.statusOfValue(forKey: "tracks", error: &tracksError) == .loaded {
                // 筛选出视频轨道
                let videoTracks = asset.tracks(withMediaType: .video)
                guard let mainVideoTrack = videoTracks.first else {
                    print("未找到有效视频轨道")
                    return
                }
                
                // 遍历格式描述提取编码信息
                for desc in mainVideoTrack.formatDescriptions {
                    guard let videoDesc = desc as? CMVideoFormatDescription else { continue }
                    let codecType = CMVideoFormatDescriptionGetCodecType(videoDesc)
                    
                    switch codecType {
                    case kCMVideoCodecType_H264:
                        print("视频编码:H.264")
                    case kCMVideoCodecType_HEVC:
                        print("视频编码:HEVC(H.265)")
                    default:
                        print("视频编码:\(codecType.description)")
                    }
                }
            } else {
                print("获取轨道信息失败:\(tracksError?.localizedDescription ?? "未知错误")")
            }
        }
    }
}

二、可选方案:QuickLook框架快速判断容器

如果只需要快速确认容器类型,也可以用QuickLook的缩略图生成器附带的元数据,但它无法获取编码格式:

import QuickLook

func quickCheckVideoContainer(from url: URL) {
    let request = QLThumbnailGenerator.Request(
        fileAt: url,
        size: .zero,
        scale: UIScreen.main.scale,
        representationTypes: .all
    )
    
    QLThumbnailGenerator.shared.generateBestRepresentation(for: request) { thumbnail, _ in
        guard let uti = thumbnail?.uti else { return }
        if uti == AVFileType.mp4.rawValue {
            print("真实容器:MP4")
        } else if uti == AVFileType.mov.rawValue {
            print("真实容器:MOV")
        }
    }
}

关键注意点

  • 必须异步加载AVAsset的属性:同步访问会阻塞主线程,甚至返回未加载完成的空值
  • 权限要到位:确保Info.plist中添加了NSPhotoLibraryUsageDescription,否则无法访问相册文件
  • UTI对应关系:苹果用UTI标识文件类型,AVFileType.mp4对应public.mpeg-4,AVFileType.mov对应com.apple.quicktime-movie,直接用封装好的常量即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:12:54