我正在尝试从HTML5视频中提取持续时间和currentTime值。我已经成功地做到了这一点,但是值以长字符串输出,而我希望保留两位小数。另外,我不想将所有时间都转换为人类可读的格式,即mm:ss
,而不仅仅是显示秒例如,我要显示00:04 / 01:27而不是4.366561 / 87.445
最后,当前时间值会随着视频的进行而更新,因此解决方案需要考虑到这一点。
谢谢!
HTML
<video id="video" src="video-url.com" preload></video>
<span class="current">0:00s</span> <span>/</span> <span class="duration">0:00s</span>
jQuery
var video = $('#video');
$(video).on('loadedmetadata', function() {
$('.duration').text(video[0].duration);
});
// Update video current time as video plays
$(video).on('timeupdate', function() {
$('.current').text(video[0].currentTime);
});
答案 0 :(得分:1)
是的,您可以使用此功能将您的电话号码格式化为MM:SS
function formatTime(time) {
if (time < 5999) {
// MM:SS
var minutes = Math.floor(time / 60);
var seconds = Math.round(time - (minutes * 60));
if (minutes < 10) { minutes = "0" + minutes }
if (seconds < 10) { seconds = "0" + seconds }
return minutes + ":" + seconds + "s"
} else {
return "Exceeds time"
}
};
这里是一个示例:
var current = 4.366561;
var duration = 87.445;
$('.duration').text(formatTime(duration));
$('.current').text(formatTime(current));
function formatTime(time) {
if (time < 5999) {
// MM:SS
var minutes = Math.floor(time / 60);
var seconds = Math.round(time - (minutes * 60));
if (minutes < 10) { minutes = "0" + minutes }
if (seconds < 10) { seconds = "0" + seconds }
return minutes + ":" + seconds + "s"
} else {
return "Exceeds time"
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="current">0:00s</span>
<span class="duration">0:00s</span>
答案 1 :(得分:0)
您可以通过使用除法和模块计算来实现:
let current = 4.366561;
let duration = 87.445;
function prettyTime(t) {
let minutes = Math.floor(t / 60);
if (minutes<10) minutes = '0' + minutes;
let seconds = Math.floor(t % 60);
if (seconds<10) seconds = '0' + seconds;
return `${minutes}:${seconds}`;
}
console.log( prettyTime(current) );
console.log( prettyTime(duration) );
示例:
function prettyTime(t) {
let minutes = Math.floor(t / 60);
if (minutes<10) minutes = '0' + minutes;
let seconds = Math.floor(t % 60);
if (seconds<10) seconds = '0' + seconds;
return `${minutes}:${seconds}`;
}
let video = $('#video');
$(video).on('loadedmetadata', function() {
$('.duration').text( prettyTime(video[0].duration) );
});
$(video).on('timeupdate', function() {
$('.current').text( prettyTime(video[0].currentTime) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="video" width="320" height="240" controls>
<source src="https://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
<source src="https://vjs.zencdn.net/v/oceans.webm" type="video/webm">
<source src="https://vjs.zencdn.net/v/oceans.ogv" type="video/ogg">
</video>
<br>
<span class="current">00:00</span> <span>/</span> <span class="duration">00:00</span>
答案 2 :(得分:0)
.toFixed()是解决方案
$(video).on('timeupdate', function() {
$('.current').text(video[0].currentTime.toFixed(2));
});