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

如何使用AVAssetReader导出.aac文件?SDAVAssetExportSession转AAC遇阻

解决SDAVAssetExportSession导出AAC文件的参数问题

我来帮你搞定这个导出AAC的问题!你现在的情况是导出.m4a正常,但改成.aac就失败,核心原因是你没有给outputFileType传入AAC格式对应的正确UTI类型。

核心解决方案

对于AAC格式的文件,你需要将outputFileType设置为AVFileType.aac.rawValue(对应的UTI是public.aac),而不是继续沿用.m4a对应的参数。

代码修改示例

你可以在导出函数里根据文件名后缀动态设置outputFileType,这样不管是.m4a还是.aac都能正常工作:

//MARK:- Export Function
func exportAssetNew(_ asset: AVAsset, fileName: String, startPost: Int64, endPost: Int64) {
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    // 根据文件名后缀判断输出格式
    let fileExtension = (fileName as NSString).pathExtension.lowercased()
    let outputFileType: String
    
    switch fileExtension {
    case "m4a":
        outputFileType = AVFileType.m4a.rawValue
    case "aac":
        outputFileType = AVFileType.aac.rawValue
    default:
        // 默认使用m4a格式
        outputFileType = AVFileType.m4a.rawValue
    }
    
    let outputURL = documentsDirectory.appendingPathComponent(fileName)
    // 初始化导出会话
    guard let exporter = SDAVAssetExportSession(asset: asset) else {
        print("Failed to create exporter")
        return
    }
    
    exporter.outputURL = outputURL
    exporter.outputFileType = outputFileType
    // 设置时间范围(注意 timescale 要和你的需求匹配,这里假设是毫秒)
    exporter.timeRange = CMTimeRange(
        start: CMTimeMake(value: startPost, timescale: 1000),
        end: CMTimeMake(value: endPost, timescale: 1000)
    )
    // 选择合适的导出预设,AVAssetExportPresetAppleM4A 兼容AAC编码,也可以根据需求调整
    exporter.exportPreset = AVAssetExportPresetAppleM4A
    
    exporter.completionHandler = { session in
        switch session.status {
        case .completed:
            print("Export success! File saved to: \(outputURL)")
        case .failed:
            print("Export failed: \(session.error?.localizedDescription ?? "Unknown error")")
        case .cancelled:
            print("Export cancelled")
        default:
            break
        }
    }
    
    exporter.startExporting()
}

额外注意事项

  • AAC是音频编码格式,而.m4a是容器格式:AAC可以封装在.m4a容器中,也可以以纯ADTS格式的.aac文件存在,设置正确的UTI是关键。
  • 确保导出预设兼容AAC:AVAssetExportPresetAppleM4A会导出带AAC编码的音频,适合.m4a和.aac两种输出格式;如果需要无损或其他编码,可调整为对应的预设。
  • 输出URL要和文件名后缀匹配:确保你的outputURL对应的文件后缀是.aac,避免格式不匹配导致的失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:43:20