如何快速将多种音频混合并保存到单个音频中

时间:2018-10-15 12:04:13

标签: swift core-audio audiokit avassetexportsession

我有多个音频文件(超过3个)。通过使用AVAudioEngineAVAudioMixerNode,我将所有音频轨道播放到一个轨道中。我想将混合音频保存在文档目录中。 提供建议以混合多个音频文件并保存在文档目录中。

谢谢

1 个答案:

答案 0 :(得分:0)

尝试一下:

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")
    }
}
}