introduce
This article mainly introduces how to obtain the total duration of the video through the js method after obtaining the URL of the video. It is compatible with web pages, APP embedded h5 pages, and applet embedded h5 pages~
For details, please refer to: https://timor419.github.io/2021/11/25/JS-getVideoDuration/
Applicable scene:
Web pages, APP embedded h5 pages, applet embedded h5 pages
JS code:
1. How to get video duration
Note: For getENVIR and checkIfIOS methods, see the link: https://blog.csdn.net/weixin_43937466/article/details/121539118
getVideoDuration(url) {
// IOS的微信小程序中无法触发onloadedmetadata
if (this.getENVIR() === 'wxapp' && this.checkIfIOS()) {
return new Promise((reslove) => {
let audio = new Audio(url);
audio.muted = true;
audio.play().then(() => audio.pause());
audio.addEventListener('loadedmetadata', function() {
reslove(parseInt((audio.duration * 1000).toString(), 10));
});
audio.muted = false;
});
}
return new Promise((reslove) => {
let video = document.createElement('video');
video.preload = 'metadata';
video.src = url;
video.onloadedmetadata = () => {
reslove(parseInt((video.duration * 1000).toString(), 10));
video = null;
};
});
},
2. Call method
const duration = this.getVideoDuration('https://cdn.webuy.ai/static/lib/resource/2021/11/25/1637813076906_4250.mp4');
console.log('视频总时长:', duration);
------------- The End -------------
License Agreement: For reprinting, please keep the original link and author.