How to get and save the mixed of multiple audios in to single audio in swift

折月煮酒 提交于 2019-12-10 11:48:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!