【发布时间】:2021-10-11 19:40:40
【问题描述】:
我有一个 AVMutableComposition 只包含我想导出到 .wav 音频文件的音频。
我发现的最简单的音频导出解决方案是使用AVAssetExportSession,就像在这个简化的示例中一样:
let composition = AVMutableComposition()
// add tracks...
let exportSession = AVAssetExportSession(asset: composition,
presetName: AVAssetExportPresetAppleM4A)!
exportSession.outputFileType = .m4a
exportSession.outputURL = someOutUrl
exportSession.exportAsynchronously {
// done
}
但它只适用于 .m4a
这个post 提到要导出到其他格式,必须使用AVAssetReader 和AVAssetWriter,但遗憾的是它没有详细说明。
我曾尝试实现它,但被卡在了这个过程中。
这是我到目前为止所拥有的(再次简化):
let composition = AVMutableComposition()
let outputSettings: [String : Any] = [
AVFormatIDKey: kAudioFormatLinearPCM,
AVLinearPCMIsBigEndianKey: false,
AVLinearPCMIsFloatKey: false,
AVLinearPCMBitDepthKey: 32,
AVLinearPCMIsNonInterleaved: false,
AVSampleRateKey: 44100.0,
AVChannelLayoutKey: NSData(),
]
let assetWriter = try! AVAssetWriter(outputURL: someOutUrl, fileType: .wav)
let input = AVAssetWriterInput(mediaType: .audio, outputSettings: outputSettings)
assetWriter.add(input)
assetWriter.startWriting()
assetWriter.startSession(atSourceTime: CMTime.zero)
input.requestMediaDataWhenReady(on: .main) {
// as I understand, I need to bring in data from my
// AVMutableComposition here...
let sampleBuffer: CMSampleBuffer = ???
input.append(sampleBuffer)
}
assetWriter.finishWriting {
// done
}
归结为我的问题:
您能否提供一个将音频从 AVMutableComposition 导出到 wav 文件的工作示例?
【问题讨论】:
标签: swift avfoundation core-audio avassetwriter