Silence-dream / Silence-dream.github.io

blog博客
https://silence-dream.github.io
3 stars 0 forks source link

js获取视频总时长,监听播放进度 #26

Open Silence-dream opened 1 year ago

Silence-dream commented 1 year ago
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <title>播放时长</title>
</head>

<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
<video id="myVideo" controls="controls">
    <source type="video/mp4" src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4">
</video>

<script>
    function videoInit(){
        let elevideo = document.getElementById('myVideo');
        elevideo.addEventListener('waiting', function () { //加载
            console.log("加载中");
        });
        elevideo.addEventListener('loadedmetadata', () => {
            //视频的总长度
            console.log('总长度:' + elevideo.duration);
            clearInterval(this.timer);
        });
        elevideo.addEventListener('play', () => {
            //播放开始执行的函数
            console.log('开始播放');
        });
        elevideo.addEventListener('playing', () => {
            //播放中
            console.log('播放中');
            this.timer = setInterval(() => {
                console.log('播放进度:' + parseFloat(elevideo.currentTime));
            }, 1000);
        });
        elevideo.addEventListener('pause', ()=> { //暂停开始执行的函数
            console.log("暂停播放");
            clearInterval( this.timer);
        });
        elevideo.addEventListener(
            'ended',
            () => {
                //结束
                console.log('播放结束');
                clearInterval(this.timer);
            },
            false
        );
    };
    videoInit()
</script>

</body>
</html>