简体   繁体   中英

Swift Export MP4 using AVAssetExportSession

I am trying to export an mp4 file within the documents directory. I am downloading that file from a remote URL and them attempting the trim it and create a new mp4 from the existing. Below is the code I am using the the exception that I am getting. This approach is working for .mov files and remote videos but not mp4.

func trimVideo(sourceURL: URL, startTime: Double, endTime: Double) {
 let fileManager = FileManager.default
 let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]

 let asset = AVAsset(url: sourceURL)

 let fileName = UUID().uuidString + ".mp4"

 var outputURL = documentDirectory.appendingPathComponent("output")
 do {
   try fileManager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil)
   outputURL = outputURL.appendingPathComponent(fileName)
 }catch let error {
   print(error)
 }

 //Remove existing file
 try? fileManager.removeItem(at: outputURL)

 guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset640x480) else { return }
 exportSession.outputURL = outputURL
 exportSession.outputFileType = AVFileType.mp4
 let timeRange = CMTimeRange(start: CMTime(seconds: startTime, preferredTimescale: 1000),
                            end: CMTime(seconds: endTime, preferredTimescale: 1000))

 exportSession.timeRange = timeRange
 exportSession.exportAsynchronously {
   switch exportSession.status {
    case .completed:
      print(outputURL.absoluteString)
    case .failed:
      print("failed \(exportSession.error.debugDescription)")
    case .cancelled:
      print("cancelled \(exportSession.error.debugDescription)")
    default: break
    }
  }
}

failed Optional(Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSUnderlyingError=0x600003f432a0 {Error Domain=NSOSStatusErrorDomain Code=-16979 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-16979), NSURL=PATH_TO_MY_FILE.mp4, NSLocalizedDescription=The operation could not be completed})

Surfacing Victor's own answer from his comment:

the problem was that I was not creating the url that I passed in with fileURLWithPath as follows. let fileURL = URL(fileURLWithPath: filePath)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM