| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451 |
- import {
- defineComponent,
- nextTick,
- onMounted,
- reactive,
- toRefs,
- watch
- } from 'vue';
- import { ref } from 'vue';
- import styles from './index.module.less';
- import iconLoop from '../../image/icon-loop.png';
- import iconLoopActive from '../../image/icon-loop-active.png';
- import iconplay from '../../image/icon-play.png';
- import iconpause from '../../image/icon-pause.png';
- import { NSlider } from 'naive-ui';
- import Vudio from 'vudio.js';
- import { getSecondRPM } from '@/helpers/utils';
- import { Slider, showToast } from 'vant';
- import tickMp3 from '../../image/tick.mp3';
- export default defineComponent({
- name: 'video-play',
- props: {
- item: {
- type: Object,
- default: () => {
- return {};
- }
- },
- show: {
- type: Boolean,
- default: false
- },
- pageVisibility: {
- type: String,
- default: ''
- },
- showModel: {
- type: Boolean,
- default: false
- },
- isEmtry: {
- type: Boolean,
- default: false
- }
- },
- emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset', 'close'],
- setup(props, { emit }) {
- const { item, isEmtry } = toRefs(props);
- const data = reactive({
- speedInKbps: '',
- timer: null as any,
- currentTime: 0,
- duration: 0.1,
- loop: false,
- dragStatus: false, // 是否开始拖动
- playState: 'pause' as 'play' | 'pause',
- vudio: null as any,
- afterMa3: true,
- count: 0
- });
- const canvasRef: any = ref();
- const audioRef: any = ref();
- const contetRef = ref();
- watch(
- () => props.show,
- val => {
- data.count = 0;
- if (val && props.item.autoPlay) {
- // data.count = 0;
- // audioRef.value.src = item.value.content;
- onToggleAudio();
- } else {
- audioRef.value.pause();
- // audioRef.value.src = '';
- data.playState = 'pause';
- // data.vudio = null;
- }
- }
- );
- // watch(
- // () => props.item,
- // () => {
- // // data.count = 0;
- // // audioRef.value.src = item.value.content;
- // onToggleAudio();
- // }
- // );
- watch(
- () => props.pageVisibility,
- val => {
- if (val === 'hidden' && props.show) {
- audioRef.value.pause();
- data.playState = 'pause';
- }
- }
- );
- // 切换音频播放
- const onToggleAudio = () => {
- if (audioRef.value.paused) {
- audioRef.value.play();
- data.playState = 'play';
- //
- nextTick(() => {
- // onInit(audioRef.value, canvasRef.value);
- // setTimeout(() => {
- // onInit(audioRef.value, canvasRef.value);
- // }, 100);
- // console.log(data.vudio, 'data.vudio');
- // if (data.vudio) {
- // data.vudio.dance();
- // }
- });
- } else {
- audioRef.value.pause();
- data.playState = 'pause';
- }
- };
- const onInit = (audio: undefined, canvas: undefined) => {
- if (!data.vudio && data.count > 1) {
- console.log(data.vudio, 'data.vudio');
- try {
- const rect = contetRef.value.getBoundingClientRect() || {
- width: 200,
- height: 200
- };
- data.vudio = new Vudio(audio, canvas, {
- effect: 'waveform',
- accuracy: 128,
- width: rect.width,
- height: rect.height,
- waveform: {
- maxHeight: 160,
- color: [
- [0, '#44D1FF'],
- [0.5, '#44D1FF'],
- [0.5, '#198CFE'],
- [1, '#198CFE']
- ],
- prettify: false
- }
- });
- data.vudio.dance();
- } catch (e) {
- console.log(e, 'e');
- }
- } else {
- }
- };
- /** 加载成功 */
- const onLoadedmetadata = () => {
- data.duration = audioRef.value?.duration;
- // onInit(audioRef.value, canvasRef.value);
- if (props.item.autoPlay && audioRef.value && props.show) {
- // data.vudio = null;
- // data.count = 0;
- onToggleAudio();
- }
- // if (audioRef.value) {
- // audioRef.value.stop = () => {
- // audioRef.value?.pause();
- // };
- // audioRef.value.onPlay = () => {
- // audioRef.value?.play();
- // onInit(audioRef.value, canvasRef.value);
- // };
- // }
- emit('loadedmetadata', audioRef.value);
- };
- /** 改变播放时间 */
- const handleChangeTime = (val: number) => {
- data.currentTime = val;
- clearTimeout(data.timer);
- data.timer = setTimeout(() => {
- audioRef.value.currentTime = val;
- data.timer = null;
- }, 60);
- };
- /** 播放结束 */
- const onEnded = () => {
- data.playState = 'pause';
- // emit('ended');
- };
- let vudio1 = null;
- const canvas1: any = ref();
- const audio1: any = ref();
- nextTick(() => {
- const rect = contetRef.value.getBoundingClientRect() || {
- width: 200,
- height: 200
- };
- vudio1 = new Vudio(audio1.value, canvas1.value, {
- effect: 'waveform',
- accuracy: 128,
- width: rect.width,
- height: rect.height,
- waveform: {
- maxHeight: 160,
- color: [
- [0, '#44D1FF'],
- [0.5, '#44D1FF'],
- [0.5, '#198CFE'],
- [1, '#198CFE']
- ],
- prettify: false
- }
- });
- vudio1.dance();
- });
- 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() {
- timer = setTimeout(() => {
- // displayElement.textContent = `视屏下载速度: 0 KB/s`;
- data.speedInKbps = `0 KB/s`;
- }, 1500);
- }
- function buffterCatch() {
- // 设定一个计时器,检查是否在指定的时间内再次触发了progress事件
- bufferTimeout = setTimeout(() => {
- if (isBuffering) {
- // 如果计时器到达且isBuffering仍为true,则认为缓存停止
- console.log('停止缓存数据。');
- isBuffering = false;
- data.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,
- // currentBytesLoaded > previousBytesLoaded
- // );
- if (currentBytesLoaded > previousBytesLoaded) {
- const timeDiff = (currentTime - previousTime) / 1000; // 时间差转换为秒
- const bytesDiff = currentBytesLoaded - previousBytesLoaded; // 字节差值
- const speed = bytesDiff / timeDiff; // 字节每秒
- if (!element.paused) {
- const kbps = speed / 1024;
- const speedInKbps = kbps.toFixed(2); // 转换为千字节每秒并保留两位小数
- if (kbps > 1024) {
- data.speedInKbps = `${Number((kbps / 1024).toFixed(2))} M/s`;
- } else {
- data.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);
- }
- data.speedInKbps = '';
- });
- // element.addEventListener('error', () => {
- // element.pause();
- // });
- };
- onMounted(() => {
- nextTick(() => {
- calculateSpeed(audioRef.value);
- });
- });
- return () => (
- <div class={styles.videoWrap}>
- <div class={styles.content}>
- <div ref={contetRef} class={styles.contentWrap}>
- <canvas ref={canvasRef}></canvas>
- <audio
- src={isEmtry.value ? '' : item.value.content}
- ref={audioRef}
- loop={data.loop}
- onLoadedmetadata={onLoadedmetadata}
- onTimeupdate={() => {
- if (data.timer && data.playState === 'pause') return;
- if (data.count <= 1) {
- data.count += 1;
- onInit(audioRef.value, canvasRef.value);
- }
- // 开始拖动时也不能更新
- if (data.dragStatus) return;
- data.currentTime = audioRef.value?.currentTime;
- }}
- onError={() => {
- console.log('error');
- audioRef.value.pause();
- data.playState = 'pause';
- }}
- onPause={() => {
- console.log('pause');
- data.playState = 'pause';
- }}
- onEnded={onEnded}
- crossorigin="anonymous"
- playsinline="false"></audio>
- {data.afterMa3 && (
- <div class={styles.tempVudio}>
- <audio ref={audio1} src={tickMp3} />
- <canvas ref={canvas1}></canvas>
- </div>
- )}
- </div>
- </div>
- <div
- class={[styles.controls, props.showModel ? '' : styles.hide]}
- onClick={(e: Event) => {
- e.stopPropagation();
- }}
- onTouchmove={(e: TouchEvent) => {
- emit('close');
- }}>
- <div class={styles.time}>
- <div>{getSecondRPM(data.currentTime)}</div>
- <div>{getSecondRPM(data.duration)}</div>
- </div>
- <div class={[styles.slider]}>
- <Slider
- step={0.01}
- class={styles.timeProgress}
- v-model={data.currentTime}
- max={data.duration}
- onUpdate:modelValue={val => {
- handleChangeTime(val);
- }}
- onDragStart={() => {
- data.dragStatus = true;
- console.log('onDragStart');
- }}
- onDragEnd={() => {
- data.dragStatus = false;
- console.log('onDragEnd');
- }}
- />
- </div>
- <div class={styles.actions} onClick={() => emit('close')}>
- <div class={styles.actionBtn} onClick={() => onToggleAudio()}>
- <img src={data.playState === 'pause' ? iconplay : iconpause} />
- </div>
- <div
- class={styles.actionBtn}
- onClick={() => {
- data.loop = !data.loop;
- if (data.loop) {
- setTimeout(() => {
- showToast('已打开循环播放');
- }, 60);
- } else {
- setTimeout(() => {
- showToast('已关闭循环播放');
- }, 60);
- }
- }}>
- <img src={data.loop ? iconLoopActive : iconLoop} />
- </div>
- <div class={styles.downloadSpeed}>{data.speedInKbps}</div>
- </div>
- </div>
- </div>
- );
- }
- });
|