首页 > 解决方案 > Java - 从播放时间中减去暂停时间

问题描述

我有两个实例变量: private Instant elapsedTime;private Instant pauseTime;

然后我有一个方法可以根据经过时间和暂停时间计算播放时间,但它没有正确执行。我目前的代码是:

public void pausePlay(boolean paused) {
        // If elapsed time isn't already made, make it
        if (elapsedTime == null) {
            elapsedTime = Instant.now();
        }
        if (paused) {
            pauseTime = Instant.now();
        } else {
            if (pauseTime != null) {
                elapsedTime = elapsedTime.plusMillis(Duration.between(elapsedTime, pauseTime).toMillis());
        }
    }
}

我第一次暂停程序时,它工作得很好。但是下一次暂停的问题是播放时间不是从程序暂停之前的位置开始计算,而是回到程序第一次暂停之前的位置。

我已经尝试在方法中的任何位置将 pauseTime 设置为 null,但它不起作用。

有什么解决办法吗?

=================================

编辑:我通过更改以下代码来修复它...

elapsedTime = elapsedTime.plusMillis(Duration.between(elapsedTime, pauseTime).toMillis());

...进入这个:

long pausedTime = Duration.between(pauseTime, Instant.now()).toMillis();
elapsedTime = elapsedTime.plusMillis(pausedTime);

标签: javatime

解决方案


经过时间量的 Duration 类

我不是很清楚,但我似乎理解您想要跟踪经过的时间以及其中有多少已暂停时间。我认为这比你的代码多一点,但还不错。下面的课程将播放时间和暂停时间视为非常对称的,并分别跟踪它们。也许您可以根据自己的需要进行调整。

使用Duration该类一段时间,例如在暂停和非暂停模式下花费了多少时间。

public class Game {

    // At most one of playTime and pauseTime is non-null
    // and signifies the game is either playing or paused since that instant.
    Instant playTime = null;
    Instant pauseTime = null;
    
    /** Not including pause time */
    Duration totalPlayTime = Duration.ZERO;
    Duration totalPauseTime = Duration.ZERO;

    /**
     * Records elapsed time.
     * Sets state to either paused or playing controlled by the argument.
     */
    public void pausePlay(boolean paused) {
        Instant now = Instant.now();
        
        // Add elapsed time since last call to either play time or pause time
        if (playTime != null) {
            totalPlayTime = totalPlayTime.plus(Duration.between(playTime, now));
        } else if (pauseTime != null) {
            totalPauseTime = totalPauseTime.plus(Duration.between(pauseTime, now));
        }
        
        if (paused) {
            playTime = null;
            pauseTime = now;
        } else {
            playTime = now;
            pauseTime = null;
        }
    }
    
}

推荐阅读