首页 > 解决方案 > Video converted from mov to mp4 on iOS can not be played on browser etc

问题描述

I wanna to convert .mov to .mp4 on iOS.

I could convert it to .mp4, but I can not play the converted file on a browser such as Chrome.

Playable on iOS and mac Safari.

Here is the code for conversion.

private func encodeVideo(at avAsset: AVURLAsset, completionHandler: ((URL?, Error?) -> Void)?)  {
        let startDate = Date()

        //Create Export session
        guard let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) else {
            completionHandler?(nil, nil)
            return
        }

        //Creating temp path to save the converted video
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
        let filePath = documentsDirectory.appendingPathComponent("rendered-Video.mp4")

        //Check if the file already exists then remove the previous file
        if FileManager.default.fileExists(atPath: filePath.path) {
            do {
                try FileManager.default.removeItem(at: filePath)
            } catch {
                completionHandler?(nil, error)
            }
        }

        exportSession.outputURL = filePath
        exportSession.outputFileType = .mp4
        exportSession.shouldOptimizeForNetworkUse = true
        let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0)
        let range = CMTimeRangeMake(start: start, duration: avAsset.duration)
        exportSession.timeRange = range

        exportSession.exportAsynchronously(completionHandler: {() -> Void in
            switch exportSession.status {
            case .failed:
                print(exportSession.error ?? "NO ERROR")
                completionHandler?(nil, exportSession.error)
            case .cancelled:
                print("Export canceled")
                completionHandler?(nil, nil)
            case .completed:
                //Video conversion finished
                let endDate = Date()

                let time = endDate.timeIntervalSince(startDate)
                print(time)
                print("Successful!")
                print(exportSession.outputURL ?? "NO OUTPUT URL")
                completionHandler?(exportSession.outputURL, nil)

            default:
                break
            }

        })
    }

How can I convert it to playable mp4 anywhere?

标签: iosswiftvideoavfoundationmp4

解决方案


尝试使用另一个AVAssetExportPreset,根据此线程AVAssetExportSession 使用 AVAssetExportPresetPassthrough 破坏输出具有已知的兼容性错误。

在此处阅读更多信息:https ://developer.apple.com/documentation/avfoundation/avassetexportsession


推荐阅读