问题
I have multiple audios files(more than 3). By using the AVAudioEngine
and AVAudioMixerNode
I am playing the all audio tracks into a single track. I want to save the mixed audio in the document directory.
Give suggestions to mix the multiple audios files and save in a document directory.
Thank you
回答1:
Try this:
func mergeAudioFiles(files: [URL], completion: @escaping (_ succeeded: Bool)->()) {
let composition = AVMutableComposition()
guard let compositionAudioTrack:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid) else {
completion(false)
return
}
for fileUrl in files {
let asset = AVURLAsset(url: fileUrl, options: nil)
let assetTrack = asset.tracks(withMediaType: AVMediaType.audio)[0]
do {
try compositionAudioTrack.insertTimeRange(assetTrack.timeRange, of: assetTrack, at: compositionAudioTrack.timeRange.duration)
} catch {}
}
guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else {
completion(false)
return
}
exporter.outputFileType = AVFileType.m4a
exporter.outputURL = URL(string: "AudioPathInDocumentsDirectory")
exporter.timeRange = compositionAudioTrack.timeRange
exporter.exportAsynchronously() {
switch exporter.status {
case .unknown,.waiting, .exporting:
print("Exported Waiting")
case .completed:
print("Exported Complete")
completion(true)
case .failed:
print("Exported Failed")
completion(false)
case .cancelled:
print("Exported Cancelled")
}
}
}
来源:https://stackoverflow.com/questions/52816376/how-to-get-and-save-the-mixed-of-multiple-audios-in-to-single-audio-in-swift