简体   繁体   English

Swift和AVAssetExportSession:为Chrome和HTML5编码MP4视频

[英]Swift & AVAssetExportSession : encode MP4 video for Chrome and HTML5

I'm trying to encode a video so that it can be read on chrome in HTML5. 我正在尝试对视频进行编码,以便可以在HTML5中的chrome上阅读它。 Unfortunately I am not able to find a codec. 不幸的是我找不到编解码器。 I have tried MP4 and Apple .mov ( H.265 ). 我已经尝试过MP4和Apple .mov(H.265)。 I can play the audio track, but there is no picture with the HTML5 player on Chrome. 我可以播放音轨,但是Chrome上的HTML5播放器没有图片。 I tried to encode in MP4 ... but it doesn't work. 我试图在MP4中编码...但是它不起作用。 The video is sent to Google Storage and displayed on Chrome with HTML5. 该视频将发送到Google Storage,并使用HTML5在Chrome上显示。 Does anyone have a solution? 有没有人有办法解决吗? Thanks in advance. 提前致谢。

func encodeVideo(videoUrl: URL, outputUrl: URL? = nil, resultClosure: @escaping (URL?) -> Void ) {

var finalOutputUrl: URL? = outputUrl

if finalOutputUrl == nil {
    var url = videoUrl
    url.deletePathExtension()
    url.appendPathExtension(".mp4")
    finalOutputUrl = url
}

if FileManager.default.fileExists(atPath: finalOutputUrl!.path) {
    print("Converted file already exists \(finalOutputUrl!.path)")
    resultClosure(finalOutputUrl)
    return
}

let asset = AVURLAsset(url: videoUrl)
if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetPassthrough) {
    exportSession.outputURL = finalOutputUrl!
    exportSession.outputFileType = AVFileTypeMPEG4
    let start = CMTimeMakeWithSeconds(0.0, 0)
    let range = CMTimeRangeMake(start, asset.duration)
    exportSession.timeRange = range
    exportSession.shouldOptimizeForNetworkUse = true
    exportSession.exportAsynchronously() {

        switch exportSession.status {
        case .failed:
            print("Export failed: \(exportSession.error != nil ? exportSession.error!.localizedDescription : "No Error Info")")
        case .cancelled:
            print("Export canceled")
        case .completed:
            resultClosure(finalOutputUrl!)
        default:
            break
        }
    }
} else {
    resultClosure(nil)
}

} }

It works in Chrome when AVAssetExportPresetHighestQuality preset is used instead of AVAssetExportPresetPassthrough . 当使用AVAssetExportPresetHighestQuality预设而不是AVAssetExportPresetPassthrough时,它可以在Chrome中AVAssetExportPresetPassthrough See full example here 在此处查看完整示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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