AVPlayer - Add Seconds to CMTime

前端 未结 4 1031
说谎
说谎 2021-02-12 15:21

How can I add 5 seconds to my current playing Time?
Actually this is my code:

CMTime currentTime = music.currentTime;

I can´t use CMTimeGet

相关标签:
4条回答
  • 2021-02-12 15:22

    Here is one way:

    CMTimeMakeWithSeconds(CMTimeGetSeconds(music.currentTime) + 5, music.currentTime.timescale);
    
    0 讨论(0)
  • 2021-02-12 15:30

    In Swift:

    private extension CMTime {
    
        func timeWithOffset(offset: TimeInterval) -> CMTime {
    
            let seconds = CMTimeGetSeconds(self)
            let secondsWithOffset = seconds + offset
    
            return CMTimeMakeWithSeconds(secondsWithOffset, preferredTimescale: timescale)
    
        }
    
    }
    
    0 讨论(0)
  • 2021-02-12 15:35

    elegant way is using CMTimeAdd

    CMTime currentTime = music.currentTime;
    CMTime timeToAdd   = CMTimeMakeWithSeconds(5,1);
    
    CMTime resultTime  = CMTimeAdd(currentTime,timeToAdd);
    
    //then hopefully 
    [music seekToTime:resultTime];
    

    to your edit: you can create CMTime struct by these ways

    CMTimeMake
    CMTimeMakeFromDictionary
    CMTimeMakeWithEpoch
    CMTimeMakeWithSeconds
    

    more @: https://developer.apple.com/library/mac/#documentation/CoreMedia/Reference/CMTime/Reference/reference.html

    0 讨论(0)
  • 2021-02-12 15:44

    Swift 4, using custom operator:

    extension CMTime {
        static func + (lhs: CMTime, rhs: TimeInterval) -> CMTime {
            return CMTime(seconds: lhs.seconds + rhs,
                          preferredTimescale: lhs.timescale)
        }
    
        static func += (lhs: inout CMTime, rhs: TimeInterval) {
            lhs = CMTime(seconds: lhs.seconds + rhs,
                          preferredTimescale: lhs.timescale)
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题