代码之家  ›  专栏  ›  技术社区  ›  Lance Samaria

AVAssetExportSession-如何从视频持续时间中修剪毫秒

  •  0
  • Lance Samaria  · 技术社区  · 4 年前

    可变成分:

    let mixComposition = AVMutableComposition()
            
    let compositionVideoTrack = mixComposition.addMutableTrack(withMediaType: .video, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
    
    let soundtrackTrack = mixComposition.addMutableTrack(withMediaType: .audio, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
    
    var insertTime = CMTime.zero
    for videoAsset in videoAssets {
        do {
    
            let videoTrack = videoAsset.tracks(withMediaType: .video)
            try compositionVideoTrack?.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration), videoAsset.tracks(withMediaType: .video)[0], at: insertTime)
    
            let audioTrack = videoAsset.tracks(withMediaType: .audio)
            try soundtrackTrack?.insertTimeRange(CMTimeRangeMake(start: CMTime.zero, duration: videoAsset.duration), videoAsset.tracks(withMediaType: .audio)[0], at: insertTime)
    
            insertTime = CMTimeAdd(insertTime, videoAsset.duration)
    
        } catch {
    
        }
    }
    

    AvassetExport会话:

    guard let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality) else { return }
    
    let start = CMTimeMakeWithSeconds(.zero, preferredTimescale: 600)
    let videoDuration = CMTimeMakeWithSeconds(mixComposition.duration, preferredTimescale: 600)
    let range = CMTimeRangeMake(start: start, duration: videoDuration)
    exporter.timeRange = range
    
    // ...
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Lance Samaria    4 年前

    trunc() 它截断任何余数,只留下一个整数。

    如果使用 AVMutableComposition()

    let mixComposition = AVMutableComposition()
    // ...
    
    let videoDuration = CMTimeGetSeconds(mixComposition.duration)
    let dub = Double(videoDuration)
    
    let durationTruncated = trunc(dub)
    print(".......truncate: ", durationTruncated)
    
    let duration = CMTimeMakeWithSeconds(durationTruncated, preferredTimescale: 600)
    let start = CMTimeMakeWithSeconds(.zero, preferredTimescale: 600)
    let range = CMTimeRangeMake(start: start, duration: duration)
    exporter.timeRange = range
    

    如果使用照片库中的url:

    let asset = AVURLAsset(url: yourLibraryUrl) // if this isn't a libraryUrl you will need to run it through asset.loadValuesAsynchronously and use the "duration" asset key to get the duration first
    let videoDuration = CMTimeGetSeconds(asset.duration)
    
    let dub = Double(videoDuration)
    let durationTruncated = trunc(dub)
    print(".......truncate: ", durationTruncated)
    
    let duration = CMTimeMakeWithSeconds(durationTruncated, preferredTimescale: 600)
    let start = CMTimeMakeWithSeconds(.zero, preferredTimescale: 600)
    let range = CMTimeRangeMake(start: start, duration: duration)
    exporter.timeRange = range