func mergeAudioFiles(audioFileUrls: NSMutableArray,completion: @escaping (URL)-> Swift.Void) {
let composition = AVMutableComposition()
for i in 0 ..< audioFileUrls.count {
let compositionAudioTrack :AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())
let asset = AVURLAsset(url: ((audioFileUrls[i] as! Dictionary<String, Any>)["soundURL"] as! URL))
let track = asset.tracks(withMediaType: AVMediaTypeAudio)[0]
let timeRange = CMTimeRange(start: CMTimeMake(0, 600), duration: CMTime(seconds: Double((audioFileUrls[i] as! Dictionary<String, Any>)["time"] as! CGFloat), preferredTimescale: track.timeRange.duration.timescale))
try! compositionAudioTrack.insertTimeRange(timeRange, of: track, at: composition.duration)
}
let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
self.mergeAudioURL = documentDirectoryURL.appendingPathComponent("audio.m4a")! as URL
let assetExport = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A)
assetExport?.outputFileType = AVFileTypeAppleM4A
assetExport?.outputURL = mergeAudioURL as URL
removeFileAtURLIfExists(url: mergeAudioURL)
assetExport?.exportAsynchronously(completionHandler:
{
switch assetExport!.status
{
case AVAssetExportSessionStatus.failed:
print("failed \(String(describing: assetExport?.error))")
case AVAssetExportSessionStatus.cancelled:
print("cancelled \(String(describing: assetExport?.error))")
case AVAssetExportSessionStatus.unknown:
print("unknown\(String(describing: assetExport?.error))")
case AVAssetExportSessionStatus.waiting:
print("waiting\(String(describing: assetExport?.error))")
case AVAssetExportSessionStatus.exporting:
print("exporting\(String(describing: assetExport?.error))")
default:
print("-----Merge audio exportation complete.\(self.mergeAudioURL)")
completion(self.mergeAudioURL)
}
})
}
所以我将用户按钮数据记录到字典数组中,字典有“soundURL” - 我根据按下哪个按钮传递声音的url,按下按钮的时间是“时间”,例如我开始录音并且用户在2.13秒后按下红色按钮会通过[“soundURL”:redURL,“time”:2:13]
代码中的问题是如果我非常快地点击按钮(如2秒内10次),它会创建10秒的音频文件,因为声音是1秒,我想要它做的是,最后的音频按下新按钮后应立即停止。所以它应该合并,就像不在一个queqe而是在一起