如何导出任意段视频?导出视频的最后X秒时出现“操作已停止”错误

时间:2016-06-15 20:01:00

标签: ios video avfoundation avassetexportsession avmutablecomposition

目标是导出某个视频的任意片段(例如,中间三分之一,后一半),但如果起点是视频的开头,AVAssetExportSession只会成功。

如果cmStartTime不为0,则AVAssetExportSession会因此错误而失败:

  

失败:可选(错误域= AVFoundationErrorDomain代码= -11841   “操作已停止”UserInfo = 0x175872d00   {NSLocalizedDescription =操作停止,   NSLocalizedFailureReason =视频无法合成。})。

    // Create main composition & its tracks
    let mainComposition = AVMutableComposition()
    let compositionVideoTrack = mainComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))
    let compositionAudioTrack = mainComposition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID(kCMPersistentTrackID_Invalid))

    // Get source video & audio tracks
    let videoURL = NSURL(fileURLWithPath: fileURL)
    let videoAsset = AVURLAsset(URL: videoURL, options: nil)
    let sourceVideoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0]
    let sourceAudioTrack = videoAsset.tracksWithMediaType(AVMediaTypeAudio)[0]

    // Define time values for video
    let timescale = Int32(600)
    let cmStartTime = CMTimeMake(Int64(CGFloat(0.5) * CGFloat(timescale)), timescale)
    let cmEndTime = CMTimeMake(10, 1)
    let timeRange = CMTimeRangeMake(cmStartTime, cmEndTime)

    // Add source tracks to composition
    do {
        try compositionVideoTrack.insertTimeRange(timeRange, ofTrack: sourceVideoTrack, atTime: cmStartTime)
        try compositionAudioTrack.insertTimeRange(timeRange, ofTrack: sourceAudioTrack, atTime: cmStartTime)
    } catch {
        printError("Error with insertTimeRange while exporting video: \(error)")
    }

    // Create video composition
    let renderSize = compositionVideoTrack.naturalSize
    let videoComposition = AVMutableVideoComposition()
    videoComposition.renderSize = renderSize
    videoComposition.frameDuration = CMTimeMake(Int64(1), Int32(frameRate))

    // Add layer instruction to video composition
    ...

    // Apply effects to video
    ...

    // Define export URL
    let exportPath = getUniqueTempPath(gMP4File)
    let exportURL = NSURL(fileURLWithPath: exportPath)

    // Create exporter
    let exporter = AVAssetExportSession(asset: mainComposition, presetName: AVAssetExportPresetHighestQuality)!
    exporter.videoComposition = videoComposition
    exporter.outputFileType = AVFileTypeMPEG4
    exporter.outputURL = exportURL
    exporter.shouldOptimizeForNetworkUse = true
    exporters.append(exporter)

    // Export video
    exporter.exportAsynchronouslyWithCompletionHandler() {
        // Finish stuff
    }

1 个答案:

答案 0 :(得分:1)

问题源于不理解CMTimeRangeMakeinsertTimeRange

CMTimeRangeMake的第二个值应该是剪辑持续时间,而不是结束时间。因此,如果您的开始时间是5秒标记,并且剪辑持续10秒,则第二个值应为10,而不是15。

atTime的{​​{1}}参数应为insertTimeRange,因为目标是创建新剪辑。换句话说,此值表示新曲目中从源曲目插入剪辑的位置。