Это решило мою проблему.
func trimSelectedAudio(){
let name = browseData.name!
if let asset = AVURLAsset(url: getDirectory().appendingPathComponent("\(tfTitle.text!).m4a")) as? AVAsset{
exportAsset(asset, fileName: name)
}
}
func exportAsset(_ asset: AVAsset, fileName:String){
let trimmedSoundFileUrl = getDirectory().appendingPathComponent("\(tfTitle.text!)_trimmed.m4a")
print("Saving to \(trimmedSoundFileUrl.absoluteString)")
if let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A){
exporter.outputFileType = AVFileType.m4a
exporter.outputURL = trimmedSoundFileUrl
let duration = CMTimeGetSeconds(asset.duration)
if duration < 5.0{
print("Audio is not song long")
return
}
let startTime = CMTimeMake(Int64(selectAudioRange.selectedMinValue), 1)
let stopTime = CMTimeMake(Int64(selectAudioRange.selectedMaxValue), 1)
exporter.timeRange = CMTimeRangeFromTimeToTime(startTime, stopTime)
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")
self.deleteFileAlreadyPresent()
// change core data data here
}
})
} else{
print("cannot create AVAssetExportSession for asset \(asset)")
}
}
func deleteFileAlreadyPresent(){
let PresentAudioUrl = getDirectory().appendingPathComponent("\(previousAudioName).m4a")
if FileManager.default.fileExists(atPath: PresentAudioUrl.path){
print("Sound exists, removing \(PresentAudioUrl.path)")
do{
if try PresentAudioUrl.checkResourceIsReachable(){
print("is reachable")
self.deleteRecordingFile(audioName: "\(previousAudioName).m4a")
self.saveTrimmedData()
}
// try FileManager.default.removeItem(atPath: trimmedSoundFileUrl.absoluteString)
} catch{
print("Could not remove \(PresentAudioUrl.absoluteString)")
}
}
}
func saveTrimmedData(){
DispatchQueue.main.async {
self.browseData.image = (self.imgToSave.image?.jpeg!)!
self.browseData.note = self.tfNotes.text
self.browseData.name = "\(self.tfTitle.text!)_trimmed"
do{
try self.context.save()
self.goToParentVC()
} catch let error as NSError{
print("Could not save \(error) \(error.userInfo)")
}
}
}