Nilesh
Nilesh

Reputation: 543

Convert .mkv file into .mp4 file in swift 3

I want to convert a .mkv file into .mp4 file, I searched a lot but did not get any solution for this.

I used below code to convert but the code not works, always getting the following error.

"Export failed: Cannot Open"

func convertVideoToMP4(_ videoURL: URL)  {
        let avAsset = AVURLAsset(url: videoURL, options: nil)

        let startDate = Foundation.Date()

        //Create Export session
        let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough)
        let documentsDirectory2 = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL

        let filePath = documentsDirectory2.appendingPathComponent("rendered-Video.mp4")
        deleteFile(filePath)
        exportSession!.outputURL = filePath
        exportSession!.outputFileType = AVFileTypeMPEG4
        exportSession!.shouldOptimizeForNetworkUse = true
        let start = CMTimeMakeWithSeconds(0.0, 0)
        let range = CMTimeRangeMake(start, avAsset.duration)
        exportSession?.timeRange = range

        exportSession!.exportAsynchronously(completionHandler: {() -> Void in
            switch exportSession!.status {
            case .failed:
                print("Export failed: \(String(describing: exportSession?.error?.localizedDescription))")
            case .cancelled:
                print("Export canceled")
            case .completed:
                //Video conversion finished
                print("Successful!")
            default:
                break
            }
        })
 }

Upvotes: 0

Views: 1385

Answers (0)

Related Questions