java - 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);
解决方案
经过时间量的 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;
}
}
}
推荐阅读
- c# - ASP.NET Core MVC - 传递给视图的模型属性在 Razor 中显示为空
- perl - Libxml - 如果满足特定条件,则替换 xml 值
- javascript - 如何在js中向上滚动到另一个div内的div?
- c++ - 如何解决模棱两可的运算符重载问题?
- excel - 查找员工的两个条目之间的时间
- windows - UWP BluetoothDevice.FromIdAsync() 返回 null
- wordpress - 如何通过api提交联系表格7数据?
- swift - 如何使用 AVPlayer 在 SwiftUI 中的视频循环之间添加平滑过渡?
- xamarin.ios - 如何在 xamarin.ios 中显示我将通过 AZURE NOTIFICATION HUB 从后端收到的图像
- android - 双击时防止底部工作表对话框片段显示两次