123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689 |
- 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 () => (
- <div class={styles.videoWrap}>
- <video
- style={{ width: '100%', height: '100%' }}
- ref={videoRef}
- id={videoID.value}
- preload="auto"
- playsinline
- webkit-playsinline
- x5-video-player-type="h5"></video>
- <div class={styles.videoPop}></div>
- <div
- class={[
- styles.controls,
- videoFroms.showAction ? '' : styles.sectionAnimate
- ]}
- onClick={(e: MouseEvent) => {
- e.stopPropagation();
- if (videoItem.value.paused()) return;
- emit('close');
- emit('reset');
- }}>
- <div class={styles.slider}>
- <NSlider
- value={videoFroms.currentTimeNum}
- step={0.01}
- max={videoFroms.durationNum}
- tooltip={false}
- onUpdate:value={(val: number) => {
- videoFroms.speedControl = false;
- videoItem.value.currentTime(val);
- videoFroms.currentTimeNum = val;
- videoFroms.currentTime = timeFormat(Math.round(val || 0));
- }}
- />
- </div>
- <div class={styles.tools}>
- {props.imagePos === 'right' ? (
- <>
- <div class={styles.actions}>
- <div class={styles.actionWrap}>
- <div class={styles.time}>
- <div
- class="plyr__time plyr__time--current"
- aria-label="Current time">
- {videoFroms.currentTime}
- </div>
- <span class={styles.line}>/</span>
- <div
- class="plyr__time plyr__time--duration"
- aria-label="Duration">
- {videoFroms.duration}
- </div>
- </div>
- </div>
- </div>
- <div class={styles.actions}>
- <div class={styles.actionWrap}>
- <div
- class={styles.downloadSpeed}
- style={{ paddingRight: '20px' }}>
- {videoFroms.speedInKbps}
- </div>
- <div
- class={styles.actionBtnSpeed}
- onClick={e => {
- e.stopPropagation();
- videoFroms.speedControl = !videoFroms.speedControl;
- }}>
- <img src={iconSpeed} />
- <div
- style={{
- display: videoFroms.speedControl ? 'block' : 'none'
- }}>
- <div
- class={styles.sliderPopup}
- onClick={(e: Event) => {
- e.stopPropagation();
- }}>
- <i
- class={styles.iconAdd}
- onClick={() => {
- if (videoFroms.defaultSpeed >= 1.5) {
- return;
- }
- if (videoItem.value) {
- videoFroms.defaultSpeed =
- (videoFroms.defaultSpeed * 10 + 1) / 10;
- videoItem.value.playbackRate(
- videoFroms.defaultSpeed
- );
- }
- }}></i>
- <NSlider
- value={videoFroms.defaultSpeed}
- step={0.1}
- max={1.5}
- min={0.5}
- vertical
- tooltip={false}
- onUpdate:value={(val: number) => {
- videoFroms.defaultSpeed = val;
- if (videoItem.value) {
- videoItem.value.playbackRate(
- videoFroms.defaultSpeed
- );
- }
- }}>
- {{
- thumb: () => (
- <div class={styles.sliderPoint}>
- {videoFroms.defaultSpeed}
- <span>x</span>
- </div>
- )
- }}
- </NSlider>
- <i
- class={[styles.iconCut]}
- onClick={() => {
- if (videoFroms.defaultSpeed <= 0.5) {
- return;
- }
- if (videoItem.value) {
- videoFroms.defaultSpeed =
- (videoFroms.defaultSpeed * 10 - 1) / 10;
- videoItem.value.playbackRate(
- videoFroms.defaultSpeed
- );
- }
- }}></i>
- </div>
- </div>
- </div>
- <button class={styles.iconReplay} onClick={onReplay}>
- <img src={iconLoop} />
- </button>
- <div
- class={styles.actionBtn}
- onClick={() => {
- videoFroms.speedControl = false;
- onToggleVideo();
- }}>
- {videoFroms.paused ? (
- <img class={styles.playIcon} src={iconplay} />
- ) : (
- <img class={styles.playIcon} src={iconpause} />
- )}
- </div>
- </div>
- </div>
- </>
- ) : (
- <>
- <div class={styles.actions}>
- <div class={styles.actionWrap}>
- <div
- class={styles.actionBtn}
- onClick={() => {
- videoFroms.speedControl = false;
- onToggleVideo();
- }}>
- {videoFroms.paused ? (
- <img class={styles.playIcon} src={iconplay} />
- ) : (
- <img class={styles.playIcon} src={iconpause} />
- )}
- </div>
- <button class={styles.iconReplay} onClick={onReplay}>
- <img src={iconLoop} />
- </button>
- <div
- class={styles.actionBtnSpeed}
- onClick={e => {
- e.stopPropagation();
- videoFroms.speedControl = !videoFroms.speedControl;
- }}>
- <img src={iconSpeed} />
- <div
- style={{
- display: videoFroms.speedControl ? 'block' : 'none'
- }}>
- <div
- class={styles.sliderPopup}
- onClick={(e: Event) => {
- e.stopPropagation();
- }}>
- <i
- class={styles.iconAdd}
- onClick={() => {
- if (videoFroms.defaultSpeed >= 1.5) {
- return;
- }
- if (videoItem.value) {
- videoFroms.defaultSpeed =
- (videoFroms.defaultSpeed * 10 + 1) / 10;
- videoItem.value.playbackRate(
- videoFroms.defaultSpeed
- );
- }
- }}></i>
- <NSlider
- value={videoFroms.defaultSpeed}
- step={0.1}
- max={1.5}
- min={0.5}
- vertical
- tooltip={false}
- onUpdate:value={(val: number) => {
- videoFroms.defaultSpeed = val;
- if (videoItem.value) {
- videoItem.value.playbackRate(
- videoFroms.defaultSpeed
- );
- }
- }}>
- {{
- thumb: () => (
- <div class={styles.sliderPoint}>
- {videoFroms.defaultSpeed}
- <span>x</span>
- </div>
- )
- }}
- </NSlider>
- <i
- class={[styles.iconCut]}
- onClick={() => {
- if (videoFroms.defaultSpeed <= 0.5) {
- return;
- }
- if (videoItem.value) {
- videoFroms.defaultSpeed =
- (videoFroms.defaultSpeed * 10 - 1) / 10;
- videoItem.value.playbackRate(
- videoFroms.defaultSpeed
- );
- }
- }}></i>
- </div>
- </div>
- </div>
- <div class={styles.downloadSpeed}>
- {videoFroms.speedInKbps}
- </div>
- </div>
- </div>
- <div class={styles.actions}>
- <div class={styles.actionWrap}>
- <div class={styles.time}>
- <div
- class="plyr__time plyr__time--current"
- aria-label="Current time">
- {videoFroms.currentTime}
- </div>
- <span class={styles.line}>/</span>
- <div
- class="plyr__time plyr__time--duration"
- aria-label="Duration">
- {videoFroms.duration}
- </div>
- </div>
- </div>
- </div>
- </>
- )}
- </div>
- </div>
- </div>
- );
- }
- });
|