I wrought this function to trim a specific part of an audio file. In the function, I'm writing to the new file two AVMetadataItems. I was trying to access these items later by rapping the URL with AvURlAsset and then accessing the AVAsset metaData /commonMetadata and both didn't contain the item I added before.
So I checked what happens before I'm exporting the file, and even though I gave exporter.metadata an array oh AVMetadataitem, its still appears to be nil before the exportation.
any one knows what is the problem?
func trimFromOffSetWithDuration(_ from: Date, startOffSet: TimeInterval, duration: TimeInterval, newfileName: String, file: URL, completion: fileExportaionBlock?) {
if let asset = AVURLAsset(url: file) as AVAsset? {
let trimmedFileUrl = documentsDirectory().appendingPathComponent(newfileName)
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A)
exporter?.outputFileType = AVFileTypeAppleM4A
exporter?.outputURL = trimmedFileUrl
let start = CMTimeMake(Int64(startOffSet), 1)
let end = CMTimeMake(Int64(startOffSet + duration), 1)
exporter?.timeRange = CMTimeRangeFromTimeToTime(start, end)
let typeMetaDataItem = AVMutableMetadataItem()
typeMetaDataItem.key = AVMetadataCommonKeyDescription as NSCopying & NSObjectProtocol
typeMetaDataItem.keySpace = AVMetadataKeySpaceCommon
typeMetaDataItem.value = TrackType.recording.rawValue as NSCopying & NSObjectProtocol
let dateMetaDataItem = AVMutableMetadataItem()
dateMetaDataItem.key = AVMetadataCommonKeyCreationDate as NSCopying & NSObjectProtocol
dateMetaDataItem.keySpace = AVMetadataKeySpaceCommon
dateMetaDataItem.value = from as NSCopying & NSObjectProtocol
exporter?.metadata? = [dateMetaDataItem, typeMetaDataItem]
exporter?.exportAsynchronously { handler in
if exporter?.status != AVAssetExportSessionStatus.completed {
print("Error while exporting \(exporter?.error?.localizedDescription ?? "unknown")")
completion?(nil)
return
}
}
completion?(trimmedFileUrl)
}
}
You should move
completion?(trimmedFileUrl)
inside the completion block ofexportAsynchronously
.