index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import {
  2. defineComponent,
  3. nextTick,
  4. onMounted,
  5. reactive,
  6. toRefs,
  7. watch
  8. } from 'vue';
  9. import { ref } from 'vue';
  10. import styles from './index.module.less';
  11. import iconLoop from '../../image/icon-loop.png';
  12. import iconLoopActive from '../../image/icon-loop-active.png';
  13. import iconplay from '../../image/icon-play.png';
  14. import iconpause from '../../image/icon-pause.png';
  15. import { NSlider } from 'naive-ui';
  16. import Vudio from 'vudio.js';
  17. import { getSecondRPM } from '@/helpers/utils';
  18. import { Slider, showToast } from 'vant';
  19. import tickMp3 from '../../image/tick.mp3';
  20. export default defineComponent({
  21. name: 'video-play',
  22. props: {
  23. item: {
  24. type: Object,
  25. default: () => {
  26. return {};
  27. }
  28. },
  29. show: {
  30. type: Boolean,
  31. default: false
  32. },
  33. pageVisibility: {
  34. type: String,
  35. default: ''
  36. },
  37. showModel: {
  38. type: Boolean,
  39. default: false
  40. },
  41. isEmtry: {
  42. type: Boolean,
  43. default: false
  44. }
  45. },
  46. emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset', 'close'],
  47. setup(props, { emit }) {
  48. const { item, isEmtry } = toRefs(props);
  49. const data = reactive({
  50. speedInKbps: '',
  51. timer: null as any,
  52. currentTime: 0,
  53. duration: 0.1,
  54. loop: false,
  55. dragStatus: false, // 是否开始拖动
  56. playState: 'pause' as 'play' | 'pause',
  57. vudio: null as any,
  58. afterMa3: true,
  59. count: 0
  60. });
  61. const canvasRef: any = ref();
  62. const audioRef: any = ref();
  63. const contetRef = ref();
  64. watch(
  65. () => props.show,
  66. val => {
  67. data.count = 0;
  68. if (val && props.item.autoPlay) {
  69. // data.count = 0;
  70. // audioRef.value.src = item.value.content;
  71. onToggleAudio();
  72. } else {
  73. audioRef.value.pause();
  74. // audioRef.value.src = '';
  75. data.playState = 'pause';
  76. // data.vudio = null;
  77. }
  78. }
  79. );
  80. // watch(
  81. // () => props.item,
  82. // () => {
  83. // // data.count = 0;
  84. // // audioRef.value.src = item.value.content;
  85. // onToggleAudio();
  86. // }
  87. // );
  88. watch(
  89. () => props.pageVisibility,
  90. val => {
  91. if (val === 'hidden' && props.show) {
  92. audioRef.value.pause();
  93. data.playState = 'pause';
  94. }
  95. }
  96. );
  97. // 切换音频播放
  98. const onToggleAudio = () => {
  99. if (audioRef.value.paused) {
  100. audioRef.value.play();
  101. data.playState = 'play';
  102. //
  103. nextTick(() => {
  104. // onInit(audioRef.value, canvasRef.value);
  105. // setTimeout(() => {
  106. // onInit(audioRef.value, canvasRef.value);
  107. // }, 100);
  108. // console.log(data.vudio, 'data.vudio');
  109. // if (data.vudio) {
  110. // data.vudio.dance();
  111. // }
  112. });
  113. } else {
  114. audioRef.value.pause();
  115. data.playState = 'pause';
  116. }
  117. };
  118. const onInit = (audio: undefined, canvas: undefined) => {
  119. if (!data.vudio && data.count > 1) {
  120. console.log(data.vudio, 'data.vudio');
  121. try {
  122. const rect = contetRef.value.getBoundingClientRect() || {
  123. width: 200,
  124. height: 200
  125. };
  126. data.vudio = new Vudio(audio, canvas, {
  127. effect: 'waveform',
  128. accuracy: 128,
  129. width: rect.width,
  130. height: rect.height,
  131. waveform: {
  132. maxHeight: 160,
  133. color: [
  134. [0, '#44D1FF'],
  135. [0.5, '#44D1FF'],
  136. [0.5, '#198CFE'],
  137. [1, '#198CFE']
  138. ],
  139. prettify: false
  140. }
  141. });
  142. data.vudio.dance();
  143. } catch (e) {
  144. console.log(e, 'e');
  145. }
  146. } else {
  147. }
  148. };
  149. /** 加载成功 */
  150. const onLoadedmetadata = () => {
  151. data.duration = audioRef.value?.duration;
  152. // onInit(audioRef.value, canvasRef.value);
  153. if (props.item.autoPlay && audioRef.value && props.show) {
  154. // data.vudio = null;
  155. // data.count = 0;
  156. onToggleAudio();
  157. }
  158. // if (audioRef.value) {
  159. // audioRef.value.stop = () => {
  160. // audioRef.value?.pause();
  161. // };
  162. // audioRef.value.onPlay = () => {
  163. // audioRef.value?.play();
  164. // onInit(audioRef.value, canvasRef.value);
  165. // };
  166. // }
  167. emit('loadedmetadata', audioRef.value);
  168. };
  169. /** 改变播放时间 */
  170. const handleChangeTime = (val: number) => {
  171. data.currentTime = val;
  172. clearTimeout(data.timer);
  173. data.timer = setTimeout(() => {
  174. audioRef.value.currentTime = val;
  175. data.timer = null;
  176. }, 60);
  177. };
  178. /** 播放结束 */
  179. const onEnded = () => {
  180. data.playState = 'pause';
  181. // emit('ended');
  182. };
  183. let vudio1 = null;
  184. const canvas1: any = ref();
  185. const audio1: any = ref();
  186. nextTick(() => {
  187. const rect = contetRef.value.getBoundingClientRect() || {
  188. width: 200,
  189. height: 200
  190. };
  191. vudio1 = new Vudio(audio1.value, canvas1.value, {
  192. effect: 'waveform',
  193. accuracy: 128,
  194. width: rect.width,
  195. height: rect.height,
  196. waveform: {
  197. maxHeight: 160,
  198. color: [
  199. [0, '#44D1FF'],
  200. [0.5, '#44D1FF'],
  201. [0.5, '#198CFE'],
  202. [1, '#198CFE']
  203. ],
  204. prettify: false
  205. }
  206. });
  207. vudio1.dance();
  208. });
  209. const calculateSpeed = (element: any) => {
  210. let previousBytesLoaded = 0;
  211. let timer: any = null;
  212. let previousTime = Date.now();
  213. let isWaiting = false;
  214. // 缓存检测状态
  215. let isBuffering = false;
  216. // 缓存检测计时器
  217. let bufferTimeout: any = null;
  218. // 设定一个检测缓存停止的时间间隔,这里我们设置为2500毫秒(2秒)
  219. const BUFFER_CHECK_INTERVAL = 2500;
  220. function resetDownloadSpeed() {
  221. timer = setTimeout(() => {
  222. // displayElement.textContent = `视屏下载速度: 0 KB/s`;
  223. data.speedInKbps = `0 KB/s`;
  224. }, 1500);
  225. }
  226. function buffterCatch() {
  227. // 设定一个计时器,检查是否在指定的时间内再次触发了progress事件
  228. bufferTimeout = setTimeout(() => {
  229. if (isBuffering) {
  230. // 如果计时器到达且isBuffering仍为true,则认为缓存停止
  231. console.log('停止缓存数据。');
  232. isBuffering = false;
  233. data.speedInKbps = '';
  234. }
  235. }, BUFFER_CHECK_INTERVAL);
  236. }
  237. element.addEventListener('progress', () => {
  238. const currentTime = Date.now();
  239. const buffered = element.buffered;
  240. let currentBytesLoaded = 0;
  241. if (buffered.length > 0) {
  242. for (let i = 0; i < buffered.length; i++) {
  243. currentBytesLoaded += buffered.end(i) - buffered.start(i);
  244. }
  245. currentBytesLoaded *= element.duration * element.seekable.end(0); // 更精确地近似字节加载量
  246. }
  247. // console.log(
  248. // 'progress',
  249. // currentBytesLoaded,
  250. // previousBytesLoaded,
  251. // currentBytesLoaded > previousBytesLoaded
  252. // );
  253. if (currentBytesLoaded > previousBytesLoaded) {
  254. const timeDiff = (currentTime - previousTime) / 1000; // 时间差转换为秒
  255. const bytesDiff = currentBytesLoaded - previousBytesLoaded; // 字节差值
  256. const speed = bytesDiff / timeDiff; // 字节每秒
  257. if (!element.paused) {
  258. const kbps = speed / 1024;
  259. const speedInKbps = kbps.toFixed(2); // 转换为千字节每秒并保留两位小数
  260. if (kbps > 1024) {
  261. data.speedInKbps = `${Number((kbps / 1024).toFixed(2))} M/s`;
  262. } else {
  263. data.speedInKbps = `${Number(speedInKbps)} KB/s`;
  264. }
  265. }
  266. previousBytesLoaded = currentBytesLoaded;
  267. previousTime = currentTime;
  268. }
  269. if (!element.paused) {
  270. // 如果1秒钟没有返回就重置数据
  271. clearTimeout(timer);
  272. resetDownloadSpeed();
  273. }
  274. if (!isWaiting) {
  275. // 如果有缓存检测计时器,则清除它
  276. if (bufferTimeout) {
  277. clearTimeout(bufferTimeout);
  278. }
  279. // 标记为正在缓存
  280. isBuffering = true;
  281. buffterCatch();
  282. }
  283. });
  284. element.addEventListener('waiting', () => {
  285. console.log('waiting');
  286. isWaiting = true;
  287. if (!element.paused) {
  288. // 如果1秒钟没有返回就重置数据
  289. clearTimeout(timer);
  290. resetDownloadSpeed();
  291. }
  292. // 如果有缓存检测计时器,则清除它
  293. if (bufferTimeout) {
  294. clearTimeout(bufferTimeout);
  295. }
  296. });
  297. element.addEventListener('canplay', () => {
  298. console.log('canplay');
  299. isWaiting = false;
  300. // 如果有缓存检测计时器,则清除它
  301. if (bufferTimeout) {
  302. clearTimeout(bufferTimeout);
  303. }
  304. // 标记为正在缓存
  305. isBuffering = true;
  306. buffterCatch();
  307. });
  308. element.addEventListener('pause', () => {
  309. clearTimeout(timer);
  310. // 如果有缓存检测计时器,则清除它
  311. if (bufferTimeout) {
  312. clearTimeout(bufferTimeout);
  313. }
  314. data.speedInKbps = '';
  315. });
  316. // element.addEventListener('error', () => {
  317. // element.pause();
  318. // });
  319. };
  320. onMounted(() => {
  321. nextTick(() => {
  322. calculateSpeed(audioRef.value);
  323. });
  324. });
  325. return () => (
  326. <div class={styles.videoWrap}>
  327. <div class={styles.content}>
  328. <div ref={contetRef} class={styles.contentWrap}>
  329. <canvas ref={canvasRef}></canvas>
  330. <audio
  331. src={isEmtry.value ? '' : item.value.content}
  332. ref={audioRef}
  333. loop={data.loop}
  334. onLoadedmetadata={onLoadedmetadata}
  335. onTimeupdate={() => {
  336. if (data.timer && data.playState === 'pause') return;
  337. if (data.count <= 1) {
  338. data.count += 1;
  339. onInit(audioRef.value, canvasRef.value);
  340. }
  341. // 开始拖动时也不能更新
  342. if (data.dragStatus) return;
  343. data.currentTime = audioRef.value?.currentTime;
  344. }}
  345. onError={() => {
  346. console.log('error');
  347. audioRef.value.pause();
  348. data.playState = 'pause';
  349. }}
  350. onPause={() => {
  351. console.log('pause');
  352. data.playState = 'pause';
  353. }}
  354. onEnded={onEnded}
  355. crossorigin="anonymous"
  356. playsinline="false"></audio>
  357. {data.afterMa3 && (
  358. <div class={styles.tempVudio}>
  359. <audio ref={audio1} src={tickMp3} />
  360. <canvas ref={canvas1}></canvas>
  361. </div>
  362. )}
  363. </div>
  364. </div>
  365. <div
  366. class={[styles.controls, props.showModel ? '' : styles.hide]}
  367. onClick={(e: Event) => {
  368. e.stopPropagation();
  369. }}
  370. onTouchmove={(e: TouchEvent) => {
  371. emit('close');
  372. }}>
  373. <div class={styles.time}>
  374. <div>{getSecondRPM(data.currentTime)}</div>
  375. <div>{getSecondRPM(data.duration)}</div>
  376. </div>
  377. <div class={[styles.slider]}>
  378. <Slider
  379. step={0.01}
  380. class={styles.timeProgress}
  381. v-model={data.currentTime}
  382. max={data.duration}
  383. onUpdate:modelValue={val => {
  384. handleChangeTime(val);
  385. }}
  386. onDragStart={() => {
  387. data.dragStatus = true;
  388. console.log('onDragStart');
  389. }}
  390. onDragEnd={() => {
  391. data.dragStatus = false;
  392. console.log('onDragEnd');
  393. }}
  394. />
  395. </div>
  396. <div class={styles.actions} onClick={() => emit('close')}>
  397. <div class={styles.actionBtn} onClick={() => onToggleAudio()}>
  398. <img src={data.playState === 'pause' ? iconplay : iconpause} />
  399. </div>
  400. <div
  401. class={styles.actionBtn}
  402. onClick={() => {
  403. data.loop = !data.loop;
  404. if (data.loop) {
  405. setTimeout(() => {
  406. showToast('已打开循环播放');
  407. }, 60);
  408. } else {
  409. setTimeout(() => {
  410. showToast('已关闭循环播放');
  411. }, 60);
  412. }
  413. }}>
  414. <img src={data.loop ? iconLoopActive : iconLoop} />
  415. </div>
  416. <div class={styles.downloadSpeed}>{data.speedInKbps}</div>
  417. </div>
  418. </div>
  419. </div>
  420. );
  421. }
  422. });