Open Lenny-Hu opened 4 years ago
使用DPlayer播放器
DPlayer
由于某些浏览器会将video渲染为浏览器厂商自定义的播放器(用来加载广告,比如QQ浏览器你),所以视频事件不是所有的浏览器都支持或者说一致,如果使用定时器延后2秒进行跳转,有些浏览器还是有些问题。其中QQ浏览器、小米自带浏览器第一次加载视频时,该方法可能会失效,并且可能导致进度条错误的情况。有些API在移动端存在第一次失效的问题可能是因为浏览器厂商的播放器还没有准备好?
经过多方测试,发现timeupdate事件大部分浏览器都兼容,并且这个时候,视频应该已经可以正常播放了。所以在该事件内,跳转播放进度,是比较可靠的,代码如下。
timeupdate
record: function (curTime) { if (curTime <= 5) { return false; } // 避免太频繁写localStorage var _time = parseInt(curTime); if (this.recordTime == _time) { return false; } this.recordTime = _time; localStorage.setItem( encodeURIComponent( decodeURIComponent(this.selected.video.url.slice(-40)) ), curTime ); }, getRecord: function () { var recordTime = localStorage.getItem( encodeURIComponent( decodeURIComponent(this.selected.video.url.slice(-40)) ) ); recordTime = parseFloat(recordTime); return isNaN(recordTime) ? 0 : recordTime; }, clearRecord: function () { return localStorage.removeItem( encodeURIComponent( decodeURIComponent(this.selected.video.url.slice(-40)) ) ); }, videoPlayer: function () { if (!this.selected.video.url) { return false; } var _this = this; this.recordTime = 0; this.isFirstPlay = true; if (this.vPlayer) { this.vPlayer.switchVideo({ url: this.selected.video.url, pic: this.detail.cover }); this.vPlayer.play(); // 切换视频时,自动播放 } else { this.vPlayer = new DPlayer({ container: document.getElementById('dplayer'), video: { url: this.selected.video.url, pic: this.detail.cover } }); // 重点在这里———————— 监听timeupdate this.vPlayer.on('timeupdate', function () { var curTime = _this.vPlayer.video.currentTime; // 当前进度大于等于1秒时再进行跳转确保兼容大部分浏览器 // isFirstPlay 标识用于限制为仅第一次播放时才跳转记录 if (curTime >= 1 && _this.isFirstPlay) { // 读取本地播放记录 var recordTime = _this.getRecord(); if ((curTime + 1) < recordTime) { _this.vPlayer.seek(recordTime); clearTimeout(_this.timer); _this.timer = setTimeout(function () { _this.vPlayer.notice('已跳转到上次播放位置'); }, 2000); } _this.isFirstPlay = false; } _this.record(curTime); }); // 监听视频播放结束,清除本地播放记录,避免下次直接跳到结尾 this.vPlayer.on('ended', function () { _this.clearRecord(); }); } },
UC浏览器,播放视频时,播放器会记住上次播放进度,可能存在重复跳转。
设置跳转时间
使用
DPlayer
播放器经过多方测试,发现
timeupdate
事件大部分浏览器都兼容,并且这个时候,视频应该已经可以正常播放了。所以在该事件内,跳转播放进度,是比较可靠的,代码如下。