Search code examples
iosperformanceavfoundationmode

iOS how to slow down specific duration of video's playback speed


I want to make part of video slow down while rest of it are normal speed, just like the slow mode video taken by iOS camera. How to do that? I've search AVFoundation but found nothing.

Thanks!


Solution

  • If you are only talking about creating this effect during playback (and not exporting it), you should be able to do so by just changing the rate property of AVPlayer at specific times. Use addBoundaryTimeObserverForTimes:queue:usingBlock: to get notified when it's time to change the rate.

    CMTime interval = CMTimeMake(10, 1);
    NSArray *times = @[[NSValue valueWithCMTime:interval]];
    
    _boundaryTimeObserver = [_avPlayer addBoundaryTimeObserverForTimes:times
                                                     queue:nil
                                                usingBlock:^{
                                                    [_weakPlayer setRate:0.5];
                                                }];
    

    The rate property works as follows:

    rate = 0.0; // Stopped
    rate = 0.5; // Half speed
    rate = 1.0; // Normal speed
    

    For slow motion playback, the AVPlayer property canPlaySlowForward must be set to true.

    Remember to remove the time observer when you're finished with it, and make sure to use an unretained reference to self or to the player within the block in order to avoid retain cycles.