Files
learning-system-mobile/components/video-player/video-player.vue
2024-08-05 16:46:58 +08:00

708 lines
22 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<view>
<view v-if="!xvideoBool || xvideoBool&&drag" id="xvideoPlayer-box" :class="fullScreenFlag?'video-box video-full-screen':'video-box'">
<div style="color:#ffffff">{{currtimeText}}</div>
<!--webkit-playsinline playsinline x5-video-player-type="h5-page-->
<!-- :src="url" <video id="xvideoPlayer" :class="fullScreenFlag?'video-scree-rotate':''" :style="{width: fullScreenFlag?videoPageHeight+'px':'100%',height: fullScreenFlag?videoPageWidth+'px': '','margin-left':fullScreenFlag?-1*(videoPageWidth/videoPageHeight*256)+'px':'','top':fullScreenFlag?videoPageHeight/2+'px':''}" -->
<video id="xvideoPlayer" :class="fullScreenFlag?'video-scree-rotate':''" :style="{width: fullScreenFlag?videoPageHeight+'px':'100%',height: fullScreenFlag?videoPageWidth+'px': '','margin-left':fullScreenFlag?-1*(videoPageHeight-videoPageWidth)/2+'px':''}"
:src="url"
:controls="false"
:enable-play-gesture="false"
:enable-progress-gesture="false"
:initial-time="initPlayingTime"
@error="error"
@touchend="onTouchend"
@play="onPlay"
@pause="onPause"
@ended="onEnded"
@timeupdate="onTimeUpdate"
@fullscreenchange="onFullScreen"
@loadeddata="onLoad"
@loadedmetadata="onMetaLoad"
@controlstoggle="onControlsToggle"
>
</video>
<view id="xplayer-control">
<!-- <view class="process-container" v-if="contrlShow" :class="fullScreenFlag?'video-scree-rotate':''" :style="{width: fullScreenFlag?videoPageHeight+'px':'100%','margin-left':fullScreenFlag?'-320px':'','top':fullScreenFlag?'300px':videoFullHeight + 'px'}"> -->
<view class="process-container" v-if="contrlShow" :class="fullScreenFlag?'video-scree-rotate':''" :style="{width: fullScreenFlag?videoPageHeight*0.98+'px':'96%','margin-top':-1*videoPageHeight*0.02+'px','margin-left':fullScreenFlag?-1*(videoPageHeight-videoPageWidth)/2-174 - (videoPageWidth-375)/2+'px':'','bottom':fullScreenFlag?'auto':'0px'}">
<view class="controller-play">
<image :src="require(playing? './images/pause.png':'./images/play.png')" @click.stop='videoOpreation'/>
</view>
<view class="currtime">{{currtime}}</view>
<!-- <cover-view v-if="drag" class='slider-container'>
<slider @change.stop="sliderChange" @changing="sliderChanging" step="1" :value="sliderValue" backgroundColor="#9f9587" activeColor="#d6d2cc" block-color="#FFFFFF" block-size="12"/>
-->
<!-- <slider v-if="!drag" disabled="true" step="1" :value="sliderValue" backgroundColor="#9f9587" activeColor="#d6d2cc" block-color="#FFFFFF" block-size="12"/> -->
<!-- </cover-view> -->
<view class='slider-container new-bar'>
<progressBar
:currentProgress="sliderValue"
:blobId="blobId"
:fullScreenFlag="fullScreenFlag"
v-on:updateProgress="updateProgressByClickBar"
v-on:getMouseDownStatus="getMouseDownStatusOfProgressBar"
:isDrag="drag"
width="100%"
></progressBar>
</view>
<view class="druationTime">{{druationTime}}</view>
<view class="druationTime">
<view id="myVideoSpeed" class="player-speed btn-speed">
<view @click="showSpeedCtrl">{{videoSpeed === 1 ? '倍速' : `${videoSpeed}x`}}</view>
<view class="speed-control" v-if="speedListShow">
<view class="speed-control-list">
<view class="li"
v-for="item in speedList"
:key="item"
@click="changeSpeed(item)"
:data-value="item"
:class="{'current': videoSpeed === Number(item)}">
{{ item }}x
</view>
</view>
</view>
</view>
</view>
<view class="controller-screen">
<image :src="require(fullScreenFlag? './images/back.png':'./images/full.png')" @click.stop='fullScreen'/>
</view>
<!-- <view v-if="fullScreenFlag" @click.stop='horizontalScreen' class="controller-screen">
<text>{{horizontalScreenFlag? '竖屏':'横屏'}}</text>
</view> -->
</view>
</view>
</view>
<view v-if="xvideoBool && !drag" class="video-box-error">
<view style="color: #ffffff;padding: 0px 50px 0px;font-size: 16px;">{{mobileVideoDragText}}</view>
<button style="display: inline-block;font-size: 14px;padding: 0px 10px;line-height: 28px;" v-if="mobileVideoDragSwitch == 'true'" @click="xvideoBoolFun">仍要使用此浏览器观看</button>
</view>
</view>
</template>
<script>
import progressBar from "@/components/video-player/progress-bar.vue";
import {mapGetters} from 'vuex'
import studyUtil from '@/utils/study.js';
import apiManage from '@/api/manage/manage.js';
// getDictCode
function agentFullScreen(){
let bool = false
let agent = navigator.userAgent
if(agent.indexOf('XiaoMi')!=-1){
bool = true
}
return bool
}
//alert(navigator.userAgent +'----'+ agentFullScreen())
export default {
components: { progressBar },
props: {
url:{
type: String,
require: true
},
// 视频链接对应的content Id
blobId: {
type: String,
default: null,
},
watermark:{
type: Boolean,
default: true
},
name:{
type: String,
default: ''
},
drag:{
type: Boolean,
default: true
},
inittime:{//默认播放的位置,第几秒
type: Number,
default: 0
},
},
data() {
return {
xvideoBool: agentFullScreen(), // 是否显示视频
contrlShow:false,//是否显示控制条
contrlShowTimeout:null,//显示控制条句柄
videoContext:null,//播放器
fullScreenFlag: false,//是否全屏
currtime:'00:00',//当前播放时间 字符串 计算后
druationTime:'00:00',//总时间 字符串 计算后
initPlayingTime:0,//指定播放的时间位置
sliderValue: 0, //控制进度条slider的值
updateState: true, //防止视频播放过程中导致的拖拽失效
playing:false,//是否在播放中
curVideo:{
duration:0,
currentTime: 0
},
touchNum:0,
speedListShow:false,
speedList:["2.0", "1.5", "1.25", "1.0", "0.75", "0.5"],
videoSpeed: 1.0, // 当前倍速:
isMousedownProgress: false, // 鼠标是否按下了进度条(并未松开)
historyTime: 0, // 当前视频
videoFullHeight: 190, // 控制条的高度
videoPageWidth: 0, // 当前页面窗口宽度
videoPageHeight: 0, // 当前页面窗口高度
// horizontalScreenFlag: true // 默认竖屏
mobileVideoDragSwitch: '', // 视频播放器扔要使用此浏览器观看
mobileVideoDragText: '', // 视频播放器妆容提示文本内容
currtimeText: 0,
currentTimeFormat: "00:00", // 当前播放进度的文字
fullTimeFormat: "00:00", // 视频总长度的文字
iosCurrentTime: 0, // ios里视频播放毫秒
};
},
computed: {
...mapGetters(['userInfo']),
},
watch:{
url(newVal,oldVal){
//console.log( 'watch url:',newVal,oldVal,this.videoContext)
//document.getElementById('xvideoPlayer').style.display = 'none'
this.videoContext.stop();
this.playing=false;
this.curVideo.currentTime = 0;
this.iosCurrentTime = 0;
this.sliderValue = 0;
this.videoSpeed = 1.0;
this.currtime = "00:00";
document.getElementsByTagName('video')[0].load()
setTimeout(()=>{
document.getElementsByTagName('video')[0].play()
},100)
//this.videoContext.load();
//document.getElementById('xvideoPlayer').style.display = 'block'
//this.videoContext=uni.createVideoContext("xvideoPlayer", this);
},
inittime(newVal,oldVal){
this.initPlayingTime=newVal;
//console.log('inittime::',newVal,oldVal)
}
},
mounted() {
var _this = this
this.initPlayingTime=this.inittime;
this.videoContext=uni.createVideoContext("xvideoPlayer", this);
// document.getElementsByTagName('video')[0].load()
uni.getSystemInfo({
success: function (info) {
//alert(info.windowWidth)
_this.videoPageWidth=info.windowWidth;
_this.videoPageHeight=info.windowHeight;
// 你可以在这里根据窗口高度进行后续操作
}
});
if(this.xvideoBool) this.dictCode();
// 每一秒更新进度条
setInterval(() => {
// 定时更新进度条
// if (this.isPlaying && !this.isMousedownProgress) {
// this.currentProgress = this.videoContext.currentTime / this.videoContext.duration;
// }
if (this.playing && !this.isMousedownProgress) {
this.iosCurrentTime = this.iosCurrentTime + 1
// this.sliderValue = this.iosCurrentTime/this.curVideo.duration * 100
}
// 定时更新进度的文字显示
this.updateProgressText();
}, 1000);
//绑定全局监听器
window.addEventListener("touchstart", (e) => {
if(this.speedListShow && !e.target.closest('.speed-control')){
this.speedListShow = false
}
},{ passive: false });
},
methods: {
xvideoBoolFun(){
this.xvideoBool = false
},
// 获取视频播放器设置开关字典
dictCode(){
var _this = this
apiManage.getDictCode('mobile_video_switch').then(res=>{
if(res.code==200 && res.data[0]){
_this.mobileVideoDragText = res.data[0].name
_this.mobileVideoDragSwitch = res.data[0].value
}
})
},
/* 点击进度条更新视频播放进度
*/
updateProgressByClickBar(type,value) {
let duration = this.curVideo.duration;
let second = Math.round(value * duration);
this.curVideo.currentTime = second;
this.sliderValue= value * 100,
this.druationTime = this.formatSeconds(duration);
this.currtime = this.formatSeconds(second);
this.iosCurrentTime = second;
//alert('1---this.currtime='+this.currtime)
// var duration=this.curVideo.duration;
// var second= value * duration;
if (duration) { //完成拖动后,计算对应时间并跳转到指定位置
if(type === 'start'){
this.updateState= false;
}
if( type === 'end'){
this.videoContext.seek(second);
this.curVideo.currentTime = second;
this.updateState= true //完成拖动后允许更新滚动条
//alert('value000------:'+value+'---'+this.curVideo.duration)
}
}
},
/* 获取鼠标是否按下了进度条
*/
getMouseDownStatusOfProgressBar(value) {
this.isMousedownProgress = value;
},
// 全屏+退出全屏
fullScreen(){
var _this = this
if(this.fullScreenFlag){
//this.videoContext.exitFullScreen();
this.fullScreenFlag=false;
// this.horizontalScreenFlag = true
this.videoFullHeight=190
if(document && document.exitFullscreen){
document.body.scrollTop = 0; // 对Safari
document.documentElement.scrollTop = 0; // 对Chrome, Firefox, IE 和 Opera
document.exitFullscreen();
}
}else{
//this.videoContext.requestFullScreen();
this.fullScreenFlag=true;
if(document.documentElement.requestFullscreen){
// document.documentElement.requestFullscreen();
}else{
window.screenTop(0)
}
uni.getSystemInfo({
success: function (info) {
_this.videoFullHeight=info.windowHeight/2 + 130;
// 你可以在这里根据窗口高度进行后续操作
}
});
}
},
// // 全屏模式下,横屏+竖屏
// horizontalScreen(){
// var _this = this
// if(this.horizontalScreenFlag){
// //this.videoContext.exitFullScreen();
// this.horizontalScreenFlag=false;
// // this.videoFullHeight=190
// }else{
// //this.videoContext.requestFullScreen();
// this.horizontalScreenFlag=true;
// // uni.getSystemInfo({
// // success: function (info) {
// // _this.videoFullHeight=info.windowHeight/2 + 130;
// // // 你可以在这里根据窗口高度进行后续操作
// // }
// // });
// }
// },
// 根据秒获取时间
formatSeconds(a) {
var hh = parseInt(a/3600);
var mm = parseInt((a-hh*3600)/60);
if(mm<10) mm = "0" + mm;
var ss = parseInt((a-hh*3600)%60);
if(ss<10) ss = "0" + ss;
if(hh<10) hh = hh == 0?'':`0${hh}:`;
var length = hh + mm + ":" + ss;
if(a>=0){
return length;
}else{
return "00:00";
}
},
changeSpeed(e) {
// 获取选择的倍速
let value = e;
this.videoSpeed = Number(value);
this.videoContext.playbackRate(this.videoSpeed);
studyUtil.setVideoSpeed(this.videoSpeed);
this.speedListShow=false;
},
showSpeedCtrl(){
if(this.speedListShow){
this.speedListShow=false;
}else{
this.speedListShow=true;
}
},
//开始+暂停
videoOpreation() {
this.playing ? this.videoContext.pause() : this.videoContext.play();
this.playing= !this.playing;
},
// 播放进度变化时触发event.detail = {currentTime, duration} 。触发频率 250ms 一次
videoUpdate(e) {
this.historyTime = e.detail.currentTime
let duration=this.curVideo.duration;
let sliderValue = e.detail.currentTime / duration * 100;
let second=sliderValue / 100 * duration;
// console.log('onTimeUpdate11111::',this.drag,second)
// if(!this.drag){
// this.videoContext.seek(second);
// return;
// }
if (this.updateState) { //判断拖拽完成后才触发更新,避免拖拽失效
this.sliderValue=sliderValue;
}else{
}
// alert(this.sliderValue)
this.druationTime = this.formatSeconds(duration);
//console.log(this.druationTime,'this.druationTime');
this.currtime = this.formatSeconds(second);
this.iosCurrentTime = second;
// alert('2---this.currtime='+this.currtime)
// var time = localStorage.getItem('videoProgressData')
// //alert(1)
// if(time && !this.drag || !this.drag && !time ){
// var arr = time&&JSON.parse(time) || {}
// if(arr[this.url] < this.sliderValue/100 || !arr[this.url]){
// arr[this.url] = this.sliderValue/100
// localStorage.setItem('videoProgressData',JSON.stringify(arr))
// }
// }
// 视频播放时本地记录视频实时播放时长,视频设置了禁止拖动时执行
if(!this.drag){
var time = localStorage.getItem('videoProgressData')
var arr = time&&JSON.parse(time) || {}
if(arr[this.blobId] < this.sliderValue/100 || !arr[this.blobId]){
arr[this.blobId] = parseFloat((this.sliderValue/100).toFixed(8))
if(arr[this.blobId]) localStorage.setItem('videoProgressData',JSON.stringify(arr))
}
}
},
//拖动过程中触发的事件
sliderChanging(e) {
//拖拽过程中,不允许更新进度条
this.updateState= false;
},
// 拖动slider完成后触发
sliderChange(e) {
var duration=this.curVideo.duration;
var second=e.detail.value / 100 * duration;
// alert(e.detail.value + '--slider--'+duration + '--' +second)
if (duration) { //完成拖动后,计算对应时间并跳转到指定位置
this.videoContext.seek(second);
this.sliderValue= e.detail.value,
this.updateState= true //完成拖动后允许更新滚动条
this.druationTime = this.formatSeconds(duration);
this.currtime = this.formatSeconds(second);
//alert('3---this.currtime='+this.currtime)
}
},
onFullScreen(e) {
this.fullScreenFlag=e.detail.fullScreen;
let divId='videowatermark';//水印
let full=e.detail.fullScreen;
let divControlId='xplayer-control';
let box=document.getElementById('xvideoPlayer-box');
let control=document.getElementById(divControlId);
let $this=this;
setTimeout(() => {
var div = document.getElementById("xvideoPlayer");
var div1 = div.firstChild;
//水印
if(full){
if($this.watermark){
var div3 = document.createElement("div");
div3.id =divId;
div3.setAttribute("class", "fullmark");
div3.innerHTML='';
for(var i=0;i<4;i++){
div3.innerHTML+='<div style="color:#ffffff;width: 40%;height: 155px;padding-left:60px;padding-top:50px; display: flex;justify-content: center; transform: rotate(-36deg);font-size:20px;">'+$this.userInfo.name+$this.userInfo.code+'</div>';
}
div3.style.cssText = "position:absolute;pointer-events: none; width: 100%;height: 100%;top:0;left:0;bottom: 0;right: 0; display: flex;justify-content: center;flex-wrap: wrap;overflow: hidden; opacity:0.3;padding-top:10px";
div1.appendChild(div3);
}
//添加控制条
div1.appendChild(control);
}else{
var hasControlDiv=div1.querySelector("#"+divControlId);
if(hasControlDiv){
box.appendChild(hasControlDiv);
}
if($this.watermark){
var markDiv=div1.querySelector("#"+divId);
if(markDiv){
div1.removeChild(markDiv);
}
}
}
},200);
this.$emit('fullscreenchange',e);
//this.fullScreenFlag ? this.videoContext.exitFullScreen() : this.videoContext.requestFullScreen();
// this.fullScreenFlag ? this.bool=true : this.bool=false;
//this.fullScreenFlag=!this.fullScreenFlag;
},
error(e){
console.log(e,'播放错误');
this.$emit('error',e);
},
onTouchend(e){
if(this.contrlShowTimeout!=null){
window.clearTimeout(this.contrlShowTimeout);
}
if(!this.fullScreenFlag){
this.contrlShow=!this.contrlShow;
}else{
if(!this.contrlShow){
this.contrlShow=true;
}
}
// this.onPlayerPause()
// this.touchNum ++
// let $this=this;
// setTimeout(()=>{
// if($this.touchNum == 1){
// // console.log('单击')
// }else if($this.touchNum >= 2){
// if($this.playing){
// $this.onPause()
// } else {
// $this.onPlay()
// }
// }
// this.touchNum = 0
// },250)
},
onLoad(e){
this.contrlShow=false;
this.$emit('loadeddata',e);
},
onMetaLoad(e){
this.curVideo.duration=Number(e.detail.duration);
this.druationTime = this.formatSeconds(this.curVideo.duration);
this.contrlShow=true;
this.$emit('loadedmetadata',e);
},
onControlsToggle(e){
console.log(e,"ControlsToggle");
},
// 开始
onPlay(){
this.videoContext.play();
this.playing=true;
let $this=this;
if(this.contrlShow){
this.contrlShowTimeout=window.setTimeout(function(){
$this.contrlShow=false;
},5000);
}
this.$emit('play')
},
onTimeUpdate(e){
this.currtimeText = this.currtimeText + 1
this.videoUpdate(e);
this.$emit('timeupdate',e)
},
/* 更新视频进度的文字显示
*/
updateProgressText() {
// console.log('updateProgressText this.videoContext::',this.videoContext,this.iosCurrentTime)
this.currentTimeFormat = this.secondTimeFormat(this.iosCurrentTime);
this.fullTimeFormat = this.secondTimeFormat(this.curVideo.duration);
},
/* 时间格式化秒格式化成xx:xx:xx
*/
secondTimeFormat(second) {
if(second<0) second = 0;
let result = parseInt(second);
let h =
Math.floor(result / 3600) < 10
? "0" + Math.floor(result / 3600)
: Math.floor(result / 3600);
let m =
Math.floor((result / 60) % 60) < 10
? "0" + Math.floor((result / 60) % 60)
: Math.floor((result / 60) % 60);
let s =
Math.floor(result % 60) < 10
? "0" + Math.floor(result % 60)
: Math.floor(result % 60);
result = `${m}:${s}`; // ${h}:
return result;
},
onPause() {
this.playing=false;
this.$emit('pause')
},
onEnded(){
this.playing=false;
if(this.fullScreenFlag){
this.fullScreen()
}
this.$emit('ended')
}
}
}
</script>
<style lang="scss" scoped>
.video-box{
width: 100%;
height: 100%;
position: relative;
}
.video-box-error{
width: 100%;
height: 110px;
padding: 55px 0;
background: #000000;
text-align: center;
display: flex;
align-items: center;
flex-wrap: wrap;
}
.video-full-screen{
position: fixed;
width: 100vw;
height: 100vh;
background: #000000;
z-index: 9999999;
display: flex;
align-items: center;
}
.video-scree-rotate{
transform: rotate(90deg);
// width: 100vw;
// height: 100vh;
position: fixed;
}
.screen{
position: relative;
}
.screen-full{
position:static;
}
.process-container{
width:100%;
padding:1% 2% 1% 2%;
height:60rpx;
max-height:60rpx;
position:absolute;
bottom:0rpx;
color:#ffffff;
left:0;
right:0;
z-index:9999;
display:flex;
align-items: center;
background:rgba(59, 57, 57, 0.2);
}
.process-container image{
max-width:30rpx;
max-height:30rpx;
text-align:center;
}
.slider-container{
z-index:13;
height:60rpx;
margin-bottom:10rpx;
flex:6;
max-width:50%;
}
.slider-container.new-bar{
margin: 7px 10px 10px 10px;
}
.controller-play{
width: 8%;
}
.controller-screen{
// width: 10%;
}
.currtime{
color: #ffffff;
font-size: 22rpx;
width: 11%;
height: 100%;
line-height: 60rpx;
text-align: center;
}
.druationTime{
color: #ffffff;
font-size: 22rpx;
width: 12%;
height: 100%;
line-height: 60rpx;
text-align: center;
}
.player-speed{
position: relative;
color: #e5e5e5;
padding: 0 0.4rem;
transition: color 0.3s;
height: 22px;
}
.btn-speed:hover .speed-control {
// visibility: visible;
}
.speed-control {
position: absolute;
//top: 180px;
transition: visibility 0.3s;
transform: translate(-50%, -100%);
}
.speed-control .speed-control-list {
list-style: none;
color: #e5e5e5;
width: 50px;
font-size: 12px;
text-align: left;
padding: 0px 0px 0px 5px;
margin: 0;
overflow: hidden;
border-radius: 4px;
background: rgba(21, 21, 21, 0.8);
}
.speed-control .speed-control-list .li {
position: relative;
display: block;
height: 25px;
line-height: 25px;
}
.speed-control .speed-control-list .li:hover {
color: #fff;
background: rgba(99, 99, 99, 0.8);
}
.speed-control .speed-control-list .li.current {
color: var(--primaryColor);
}
</style>