在iOS上从mov转换为mp4的视频无法在浏览器等上播放

时间:2019-01-14 09:43:17

标签: ios swift video avfoundation mp4

我想在iOS上将.mov转换为.mp4

我可以将其转换为.mp4,但无法在Chrome等浏览器上播放转换后的文件。

可在iOS和Mac Safari上播放。

这是转换代码。

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
            }

        })
    }

如何在任何地方将其转换为可播放的mp4?

1 个答案:

答案 0 :(得分:0)

尝试使用另一个AVAssetExportPreset, 根据此线程AVAssetExportSession using AVAssetExportPresetPassthrough breaking output已知的兼容性错误。

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