Edit a portion of video (using AVFoundation)

时间:2016-07-11 21:27:50

标签: swift video avmutablecomposition cmtime

I have some code, provided below. This will take 2 videos assets, and insert the 2nd asset into the first asset. As of right now I am calling a new AVMutableComposition every time and returning a whole new composition, which is time consuming. I would imagine there is a way to remove a section of video, insert another section, without having to make an entire composition. Any suggestions? (Code works, Really looking for time consumption decrease).

1) Is there a way to just change a portion of the video instead of (This is what I am doing currently every time I need to change a video)

  • 1) making a NEW AVMutableComposition
  • 2) Adding the first video
  • 3) Adding second video
  • 4) Adding last portion of first video

Or is there a way to ... (What I would like to do instead)

  • 1) Obtain first video
  • 2) Go to set time that I want changed (say at 10 seconds)
  • 3) Remove amount of time I want out, then insert time of second video
  • 4) There would be no step 4 as I would only be changing a portion of video, and not recreating an entire new one.

My current code

    let mixComposition = AVMutableComposition()

    let firstTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
    do {
        try firstTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, CMTime(seconds: 10, preferredTimescale: 600)), ofTrack: firstAsset.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: kCMTimeZero)
    } catch _ {
        print("Failed to load first track")
    }

    let secondTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
    do {
        try secondTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, secondAsset.duration), ofTrack: secondAsset.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: CMTime(seconds: 10, preferredTimescale: 600))

    } catch _ {
        print("Failed to load second track")
    }

    let thirdTrack = mixComposition.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
    do {
        try thirdTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, secondAsset.duration+CMTime(seconds: 10, preferredTimescale: 600)), ofTrack: firstAsset.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: CMTime(seconds: 10, preferredTimescale: 600))

    } catch _ {
        print("Failed to load second track")
    }

0 个答案:

没有答案