如何快速将多种音频混合并保存到单个音频中 [英] How to get and save the mixed of multiple audios in to single audio in swift
本文介绍了如何快速将多种音频混合并保存到单个音频中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有多个音频文件(超过3个)。通过使用 AVAudioEngine
和 AVAudioMixerNode
,我可以将所有音频轨道播放到一个轨道中。我想将混合音频保存在文档目录中。
提供建议以混合多个音频文件并保存在文档目录中。
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.
谢谢
推荐答案
尝试一下:
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")
}
}
}
这篇关于如何快速将多种音频混合并保存到单个音频中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文