import { defineComponent, nextTick, onMounted, onUnmounted, reactive, toRefs, watch } from 'vue'; import TCPlayer from 'tcplayer.js'; import 'tcplayer.js/dist/tcplayer.min.css'; // import 'plyr/dist/plyr.css'; // import Plyr from 'plyr'; import { ref } from 'vue'; import styles from './video.module.less'; import iconplay from '../image/icon-pause.png'; import iconpause from '../image/icon-play.png'; // import iconReplay from '../image/icon-replay.png'; import iconLoop from '../image/icon-loop.svg'; import iconLoopActive from '../image/icon-loop-active.svg'; import iconSpeed from '../image/icon-speed.png'; import { NSlider } from 'naive-ui'; export default defineComponent({ name: 'video-play', props: { item: { type: Object, default: () => { return {}; } }, showModel: { type: Boolean, default: false }, isEmtry: { type: Boolean, default: false }, imagePos: { type: String, default: 'left' } }, emits: [ 'canplay', 'pause', 'togglePlay', 'ended', 'reset', 'error', 'close', 'loadedmetadata' ], setup(props, { emit, expose }) { const { item, isEmtry } = toRefs(props); const videoFroms = reactive({ paused: true, speedInKbps: '', currentTimeNum: 0, currentTime: '00:00', durationNum: 0, duration: '00:00', showBar: true, showAction: true, loop: false, speedControl: false, speedStyle: { left: '1px' }, defaultSpeed: 1 // 默认速度 }); const videoRef = ref(); const videoItem = ref(); const videoID = ref('video' + Date.now() + Math.floor(Math.random() * 100)); // 对时间进行格式化 const timeFormat = (num: number) => { if (num > 0) { const m = Math.floor(num / 60); const s = num % 60; return (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s); } else { return '00:00'; } }; // 如果视屏异常后,需要重新播放视屏 const onPlay = () => { if (videoItem.value) { videoItem.value.src(item.value.content); emit('reset'); } }; // const toggleHideControl = (isShow: false) => { videoFroms.showBar = isShow; videoFroms.speedControl = false; }; const onReplay = () => { videoFroms.speedControl = false; if (!videoItem.value) return; videoItem.value.currentTime(0); }; // 切换音频播放 const onToggleVideo = (e?: MouseEvent) => { e?.stopPropagation(); if (videoFroms.paused) { videoItem.value.play(); videoFroms.paused = false; } else { videoItem.value.pause(); videoFroms.paused = true; } emit('togglePlay', videoFroms.paused); }; const videoTimer = null as any; let videoTimerErrorCount = 0; const handlePlayVideo = () => { if (videoTimerErrorCount > 5) { return; } clearTimeout(videoTimer); nextTick(() => { videoItem.value?.play().catch((err: any) => { // console.log('🚀 ~ err:', err) // videoTimer = setTimeout(() => { // if (err?.message?.includes('play()')) { // // emit('play'); // } // handlePlayVideo(); // }, 1000); }); }); videoTimerErrorCount++; }; const __init = () => { if (videoItem.value) { videoItem.value.poster(props.item.coverImg); // 封面 videoItem.value.src(item.value.content + '?t=4'); // url 播放地址 videoItem.value.playbackRate(videoFroms.defaultSpeed); // 初步加载时 videoItem.value.one('loadedmetadata', () => { // console.log(' Loading metadata'); videoItem.value.playbackRate(videoFroms.defaultSpeed); // 获取时长 videoFroms.duration = timeFormat( Math.round(videoItem.value.duration()) ); videoFroms.durationNum = videoItem.value.duration(); emit('canplay'); emit('loadedmetadata', videoItem.value); if (item.value.autoPlay && videoItem.value) { // videoItem.value?.play() nextTick(() => { videoTimerErrorCount = 0; videoItem.value.currentTime(0); nextTick(handlePlayVideo); }); } }); // 视频开始播放 videoItem.value.on('play', () => { emit('close'); emit('canplay'); }); // 视频播放时加载 videoItem.value.on('timeupdate', () => { videoFroms.currentTime = timeFormat( Math.round(videoItem.value?.currentTime() || 0) ); videoFroms.currentTimeNum = videoItem.value.currentTime(); }); // 视频播放结束 videoItem.value.on('ended', () => { videoFroms.paused = true; emit('ended'); }); // videoItem.value.on('pause', () => { videoFroms.paused = true; emit('pause'); }); videoItem.value.on('playing', () => { videoFroms.paused = false; }); videoItem.value.on('canplay', (e: any) => { // 获取时长 videoFroms.duration = timeFormat( Math.round(videoItem.value.duration()) ); videoFroms.durationNum = videoItem.value.duration(); emit('canplay'); }); // 视频播放异常 videoItem.value.on('error', (e: any) => { emit('error'); console.log(e, 'error'); // element.pause(); videoItem.value?.pause(); }); } }; const calculateSpeed = (element: any) => { let previousBytesLoaded = 0; let timer: any = null; let previousTime = Date.now(); let isWaiting = false; // 缓存检测状态 let isBuffering = false; // 缓存检测计时器 let bufferTimeout: any = null; // 设定一个检测缓存停止的时间间隔,这里我们设置为2500毫秒(2秒) const BUFFER_CHECK_INTERVAL = 2500; function resetDownloadSpeed(time = 1500) { timer = setTimeout(() => { // displayElement.textContent = `视屏下载速度: 0 KB/s`; videoFroms.speedInKbps = `0 KB/s`; }, time); } function buffterCatch() { // 设定一个计时器,检查是否在指定的时间内再次触发了progress事件 bufferTimeout = setTimeout(() => { if (isBuffering) { // 如果计时器到达且isBuffering仍为true,则认为缓存停止 console.log('停止缓存数据。'); isBuffering = false; videoFroms.speedInKbps = ''; } }, BUFFER_CHECK_INTERVAL); } element.addEventListener('progress', () => { const currentTime = Date.now(); const buffered = element.buffered; let currentBytesLoaded = 0; if (buffered.length > 0) { for (let i = 0; i < buffered.length; i++) { currentBytesLoaded += buffered.end(i) - buffered.start(i); } currentBytesLoaded *= element.duration * element.seekable.end(0); // 更精确地近似字节加载量 } console.log( 'progress', currentBytesLoaded > previousBytesLoaded, '------ 加载中' ); if (currentBytesLoaded > previousBytesLoaded) { const timeDiff = (currentTime - previousTime) / 1000; // 时间差转换为秒 const bytesDiff = currentBytesLoaded - previousBytesLoaded; // 字节差值 const speed = bytesDiff / timeDiff; // 字节每秒 console.log(timeDiff, bytesDiff, speed); console.log(element.paused, 'element.paused'); if (!element.paused) { const kbps = speed / 1024; const speedInKbps = kbps.toFixed(2); // 转换为千字节每秒并保留两位小数 if (kbps > 1024) { videoFroms.speedInKbps = `${Number( (kbps / 1024).toFixed(2) )} M/s`; } else { videoFroms.speedInKbps = `${Number(speedInKbps)} KB/s`; } } previousBytesLoaded = currentBytesLoaded; previousTime = currentTime; } if (!element.paused) { // 如果1秒钟没有返回就重置数据 clearTimeout(timer); resetDownloadSpeed(); } if (!isWaiting) { // 如果有缓存检测计时器,则清除它 if (bufferTimeout) { clearTimeout(bufferTimeout); } // 标记为正在缓存 isBuffering = true; buffterCatch(); } }); element.addEventListener('waiting', () => { console.log('waiting'); isWaiting = true; if (!element.paused) { // 如果1秒钟没有返回就重置数据 clearTimeout(timer); resetDownloadSpeed(); } // 如果有缓存检测计时器,则清除它 if (bufferTimeout) { clearTimeout(bufferTimeout); } }); element.addEventListener('canplay', () => { console.log('canplay'); isWaiting = false; // 如果有缓存检测计时器,则清除它 if (bufferTimeout) { clearTimeout(bufferTimeout); } // 标记为正在缓存 isBuffering = true; buffterCatch(); }); element.addEventListener('pause', () => { clearTimeout(timer); // 如果有缓存检测计时器,则清除它 if (bufferTimeout) { clearTimeout(bufferTimeout); } videoFroms.speedInKbps = ''; }); element.addEventListener('error', () => { element.pause(); videoItem.value?.pause(); }); }; onMounted(() => { videoItem.value = TCPlayer(videoID.value, { appID: '', controls: false }); // player-container-id 为播放器容器 ID,必须与 html 中一致 __init(); nextTick(() => { calculateSpeed(videoRef.value); }); }); const stop = () => { videoItem.value.currentTime(0); videoItem.value.pause(); }; const pause = () => { videoItem.value.pause(); }; onUnmounted(() => { if (videoItem.value) { videoItem.value.pause(); videoItem.value.src(''); videoItem.value.dispose(); } }); watch( () => props.item, () => { // console.log(item.value, 'value----'); videoItem.value.pause(); videoItem.value.currentTime(0); if (item.value?.id) { // videoItem.value.poster(props.item.coverImg); // 封面 // videoItem.value.src(item.value.content); // url 播放地址 __init(); videoFroms.paused = true; } } ); watch( () => props.showModel, () => { // console.log(props.showModel, 'props.showModel') videoFroms.showAction = props.showModel; videoFroms.speedControl = false; } ); expose({ onPlay, stop, pause, // changePlayBtn, toggleHideControl }); return () => (
{ e.stopPropagation(); if (videoItem.value.paused()) return; emit('close'); emit('reset'); }}>
{ videoFroms.speedControl = false; videoItem.value.currentTime(val); videoFroms.currentTimeNum = val; videoFroms.currentTime = timeFormat(Math.round(val || 0)); }} />
{props.imagePos === 'right' ? ( <>
{videoFroms.currentTime}
/
{videoFroms.duration}
{videoFroms.speedInKbps}
{ e.stopPropagation(); videoFroms.speedControl = !videoFroms.speedControl; }}>
{ e.stopPropagation(); }}> { if (videoFroms.defaultSpeed >= 1.5) { return; } if (videoItem.value) { videoFroms.defaultSpeed = (videoFroms.defaultSpeed * 10 + 1) / 10; videoItem.value.playbackRate( videoFroms.defaultSpeed ); } }}> { videoFroms.defaultSpeed = val; if (videoItem.value) { videoItem.value.playbackRate( videoFroms.defaultSpeed ); } }}> {{ thumb: () => (
{videoFroms.defaultSpeed} x
) }}
{ if (videoFroms.defaultSpeed <= 0.5) { return; } if (videoItem.value) { videoFroms.defaultSpeed = (videoFroms.defaultSpeed * 10 - 1) / 10; videoItem.value.playbackRate( videoFroms.defaultSpeed ); } }}>
{ videoFroms.speedControl = false; onToggleVideo(); }}> {videoFroms.paused ? ( ) : ( )}
) : ( <>
{ videoFroms.speedControl = false; onToggleVideo(); }}> {videoFroms.paused ? ( ) : ( )}
{ e.stopPropagation(); videoFroms.speedControl = !videoFroms.speedControl; }}>
{ e.stopPropagation(); }}> { if (videoFroms.defaultSpeed >= 1.5) { return; } if (videoItem.value) { videoFroms.defaultSpeed = (videoFroms.defaultSpeed * 10 + 1) / 10; videoItem.value.playbackRate( videoFroms.defaultSpeed ); } }}> { videoFroms.defaultSpeed = val; if (videoItem.value) { videoItem.value.playbackRate( videoFroms.defaultSpeed ); } }}> {{ thumb: () => (
{videoFroms.defaultSpeed} x
) }}
{ if (videoFroms.defaultSpeed <= 0.5) { return; } if (videoItem.value) { videoFroms.defaultSpeed = (videoFroms.defaultSpeed * 10 - 1) / 10; videoItem.value.playbackRate( videoFroms.defaultSpeed ); } }}>
{videoFroms.speedInKbps}
{videoFroms.currentTime}
/
{videoFroms.duration}
)}
); } });