I'm creating a simple audio editing tool to trim and delete from an audio. I implemented the trim function and it is working fine. However I searched and tried to implement the delete function and here is my code:
func deleteExportAsset(_ asset: AVAsset, fileName: String, completeAudioTime: CGFloat) -> URL {
print("\(#function)")
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let trimmedSoundFileURL = documentsDirectory.appendingPathComponent(fileName)
print("saving to \(trimmedSoundFileURL.absoluteString)")
if FileManager.default.fileExists(atPath: trimmedSoundFileURL.absoluteString) {
print("sound exists, removing \(trimmedSoundFileURL.absoluteString)")
do {
if try trimmedSoundFileURL.checkResourceIsReachable() {
print("is reachable")
}
try FileManager.default.removeItem(atPath: trimmedSoundFileURL.absoluteString)
} catch {
print("could not remove \(trimmedSoundFileURL)")
print(error.localizedDescription)
}
}
print("creating export session for \(asset)")
if let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) {
exporter.outputFileType = AVFileType.m4a
exporter.outputURL = trimmedSoundFileURL
let timeRange1 = CMTimeRangeFromTimeToTime(CMTime(seconds: 0, preferredTimescale: 100), CMTime(seconds: endTimeOfRange1, preferredTimescale: 100))
let timeRange2 = CMTimeRangeFromTimeToTime(CMTime(seconds: startTimeOfRange2)), preferredTimescale: 100), CMTime(seconds: Double(completeAudioTime), preferredTimescale: 100))
exporter.timeRange = CMTimeRangeGetUnion(timeRange1, timeRange2)
// do it
exporter.exportAsynchronously(completionHandler: {
print("export complete \(exporter.status)")
switch exporter.status {
case AVAssetExportSessionStatus.failed:
if let e = exporter.error {
print("export failed \(e)")
}
case AVAssetExportSessionStatus.cancelled:
print("export cancelled \(String(describing: exporter.error))")
default:
print("export complete")
}
})
} else {
print("cannot create AVAssetExportSession for asset \(asset)")
}
return trimmedSoundFileURL
}
what I'm doing here is creating 2 Ranges. Range1 from 0 ->time1 and Range2 from time2->endOfAudio. (I want to delete from time1 -> time2)
then I'm creating the union between 2 ranges. however, nothing is happening to the audio. It is saved exactly like it was before this function.