// 更新播放时长数据 const currentTime = Date.now(); this.playTime += (currentTime - this.startTime ) / 6000; this.startTime = currentTime;
// 播放完成事件
.onFinish(() => {
// 其他业务逻辑
// 更新播放时长变量
const currentTime = Date.now();
this.playTime += (currentTime - this.startTime ) / 6000;
this.startTime = currentTime;
}) 播放视频时设置定时器,及时同步时长数据,避免播放时长更新不及时。
应根据具体业务需要设置定时器触发间隔,此处以10秒钟更新一次时长为例:
@Entry
@Component
struct PlayTimeFixPage {
@State playTime: number = 0; // 单位:毫秒
private startTime: number = Date.now();
private timer: number = -1;
aboutToAppear() {
this.timer = setInterval(() => {
const now = Date.now();
this.playTime += (now - this.startTime);
this.startTime = now;
}, 10000);
}
aboutToDisappear() {
clearInterval(this.timer);
}
/* 工具:毫秒 → 时:分:秒 */
formatTime(ms: number): string {
const total = Math.floor(ms / 1000);
const h = Math.floor(total / 3600).toString().padStart(2, '0');
const m = Math.floor((total % 3600) / 60).toString().padStart(2, '0');
const s = (total % 60).toString().padStart(2, '0');
return `${h}:${m}:${s}`;
}
build() {
Column({ space: 20 }) {
Text(`播放时长:${this.formatTime(this.playTime)}`)
.fontSize(24);
Text('10 秒同步一次')
.fontSize(14)
.fontColor('#999');
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center);
}
}