首页 文章

NSDate和AVPlayerItem.currentTime

提问于
浏览
0

我知道有很多主题,但我找不到解决问题的方法 .

我有一个AVPlayerItem,我希望currentTime属性(CMTime)转换为我的音乐播放器的可读格式 .

这是我的代码:

NSDate *seconds = [[NSDate alloc] initWithTimeIntervalSinceNow:CMTimeGetSeconds(self.playerItem.currentTime)];

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH:mm:ss"];

self.currentTimeLabel.text = [NSString stringWithFormat:@"%@", [timeFormatter stringFromDate:seconds]];

它有效,但它增加了1小时的播放时间 . 我怎么能减去那个小时?

谢谢!

2 回答

  • 0

    试试这段代码,

    SWIFT代码:

    delclare

    var playerVal = AVPlayer()
    

    然后在你想要的地方调用以下方法,

    func updateTime() {
    
            let currentTime = Float(CMTimeGetSeconds(playerVal.currentTime()))
            let minutes = currentTime/60
            let seconds = currentTime - minutes * 60
    
            startValue.text = NSString(format: "%.2f:%.2f", minutes,seconds) as String
    
        }
    

    objective-C代码:

    delclare

    AVPlayer playerVal;
    

    然后在你想要的地方调用以下方法,

    - (void)updateTime {
        Float currentTime = CMTimeGetSeconds([playerVal currentTime]);
        Float minutes = currentTime/60;
        Float seconds = (currentTime - minutes) * 60;
        startValue.text = [NSString stringWithFormat:@"%.2f:%.2f", minutes,seconds];
    }
    

    它为我工作,希望它有所帮助

  • 3

    thx,我稍微改进了一下:

    float currentTime = CMTimeGetSeconds([self.audioStreamPlayer currentTime]);
    
    int seconds = (int) currentTime;
    int minutes = (int) currentTime/60;
    int hours = (int) ((currentTime/60)/60);
    
    NSString *hoursString = [NSString stringWithFormat:@"%d",hours];
    NSString *minutesString = [NSString stringWithFormat:@"%d",minutes];
    NSString *secondsString = [NSString stringWithFormat:@"%d",seconds % 60];
    
    if (hoursString.length == 1) {
        hoursString = [NSString stringWithFormat:@"0%d", hours];
    }
    if (minutesString.length == 1) {
        minutesString = [NSString stringWithFormat:@"0%d",minutes];
    }
    if (secondsString.length == 1) {
        secondsString = [NSString stringWithFormat:@"0%d", seconds % 60];
    }
    
    
    
    self.currentTimeLabel.text = [NSString stringWithFormat:@"%@:%@:%@", hoursString, minutesString, secondsString];
    

    作品!

相关问题