AVPlayer - 添加秒数到CMTime

20
我该如何将当前播放时间增加5秒?
这是我的代码:
CMTime currentTime = music.currentTime;

我无法使用CMTimeGetSeconds(),因为我需要CMTime格式。 谢谢您的回答… 编辑:如何为CMTime设置变量?
4个回答

33

这是一种方法:

CMTimeMakeWithSeconds(CMTimeGetSeconds(music.currentTime) + 5, music.currentTime.timescale);

当我将“+5”替换为“-5”时,它无法工作...你知道哪里出了问题吗? - Lorenz Wöhr
当前时间是多少秒?也许这个数字会变成负数? - BlueVoodoo
1
这是我的代码:CMTime currentTime = music.currentTime; float currentTimeInt = CMTimeGetSeconds(currentTime);if (currentTimeInt > 5) { CMTime newTime = CMTimeMakeWithSeconds(CMTimeGetSeconds(music.currentTime) - 5, music.currentTime.timescale); [music seekToTime:newTime]; } else { NSLog(@"错误"); } - Lorenz Wöhr
该值不会因为负数而改变。我省略了if语句。 - Lorenz Wöhr
现在值已经改变了 :) 但是我无法使用seekToTime:(按下时没有任何反应)。你知道为什么吗? - Lorenz Wöhr
显示剩余4条评论

25

优雅的方式是使用CMTimeAdd

CMTime currentTime = music.currentTime;
CMTime timeToAdd   = CMTimeMakeWithSeconds(5,1);

CMTime resultTime  = CMTimeAdd(currentTime,timeToAdd);

//then hopefully 
[music seekToTime:resultTime];

关于编辑方面的问题:

你可以通过以下方式创建CMTime结构。

CMTimeMake
CMTimeMakeFromDictionary
CMTimeMakeWithEpoch
CMTimeMakeWithSeconds

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

该链接是苹果官方文档中关于CMTime的参考资料。

'AVPlayer' 可能无法响应 'setCurrentTime'。 - Lorenz Wöhr
将“CMTime”发送到不兼容类型的参数“NSTimeInterval”(又名“double”) - Lorenz Wöhr
也许你应该使用 [music seekToTime: resultTime]。 - tomasgatial

5

在Swift中:

private extension CMTime {

    func timeWithOffset(offset: TimeInterval) -> CMTime {

        let seconds = CMTimeGetSeconds(self)
        let secondsWithOffset = seconds + offset

        return CMTimeMakeWithSeconds(secondsWithOffset, preferredTimescale: timescale)

    }

}

1

使用自定义运算符的Swift 4:

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)
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接