Swift导出.band文件报错:GarageBand提示文件损坏或格式错误
导出.band文件到GarageBand提示损坏的解决方案
你的核心问题是仅修改了文件扩展名,并未生成真正的GarageBand项目文件:
-.band是GarageBand专属的项目容器,本质是包含元数据、音频片段、项目设置的目录包,不是单一音频文件格式
- AVAssetExportSession只能导出标准音频格式(如AIFF、MP3、WAV),直接改后缀会导致GarageBand无法识别非标准的.band结构
正确实现思路
由于iOS没有公开的GarageBand项目创建API,可行方案分为两步:
- 导出GarageBand原生支持的标准音频文件(如WAV、AIFF)
- 引导用户在GarageBand中导入该音频并保存为.band项目
修改后的代码示例
先导出兼容格式的音频,再让用户通过系统分享流程导入GarageBand:
func copyAudioFileToDocuments(ringtone: Ringtone?) async throws -> URL? { guard let ringtone, let documentsURL = ringtone.url else { return nil } let asset = AVURLAsset(url: documentsURL) let exportAudioMix = AVMutableAudioMix() guard let track = try await asset.load(.tracks).last else { return nil } let start = ringtone.info.startTime let length = ringtone.info.endTime - ringtone.info.startTime let exportTimeRange = CMTimeRange(start: .init(seconds: start, preferredTimescale: 1), duration: .init(seconds: length, preferredTimescale: 1)) // 导出为GarageBand完美支持的WAV格式 let destinationURL = Constants.cachesDirectory.appendingPathComponent("\(ringtone.id).wav") try await exportAudio(from: track, mix: exportAudioMix, exportTimeRange: exportTimeRange, to: destinationURL) return destinationURL } func exportAudio(from track: AVAssetTrack, mix: AVAudioMix? = nil, exportTimeRange: CMTimeRange? = nil, to destinationURL: URL) async throws { let composition = AVMutableComposition() let compositionAudioTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) let duration = try await track.asset?.load(.duration) try compositionAudioTrack?.insertTimeRange(CMTimeRangeMake(start: .zero, duration: duration ?? .init()), of: track, at: .zero) let exportSession = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetPassthrough) if let exportTimeRange { exportSession?.timeRange = exportTimeRange } exportSession?.outputURL = destinationURL exportSession?.audioMix = mix // 指定WAV输出格式,避免格式不兼容问题 exportSession?.outputFileType = AVFileType.wav if FileManager.default.fileExists(atPath: destinationURL.path) { try FileManager.default.removeItem(at: destinationURL) } try await exportSession?.exportAsync() }
后续操作建议
导出WAV文件后,可通过UIDocumentInteractionController唤起系统分享菜单,让用户选择GarageBand打开该音频,用户在GarageBand内即可将音频保存为.band项目文件。
内容的提问来源于stack exchange,提问作者Sevak Tadevosyan
相关产品推荐
相关产品推荐

