video-play.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 './video.module.less';
  11. import { postMessage } from '@/helpers/native-message';
  12. // import iconLoop from '../image/icon-loop.svg';
  13. // import iconLoopActive from '../image/icon-loop-active.svg';
  14. // import iconplay from '../image/icon-play.svg';
  15. // import iconpause from '../image/icon-pause.svg';
  16. import {
  17. // iconVideoBg,
  18. iconLoop,
  19. iconLoopActive,
  20. iconPlay,
  21. iconPause,
  22. iconSpeed
  23. } from '../image/icons.json';
  24. import TCPlayer from 'tcplayer.js';
  25. import 'tcplayer.js/dist/tcplayer.min.css';
  26. import { showToast, Slider } from 'vant';
  27. import { handleShowVip, state } from '@/state';
  28. // 秒转分
  29. export const getSecondRPM = (second: number, type?: string) => {
  30. if (isNaN(second)) return '00:00';
  31. const mm = Math.floor(second / 60)
  32. .toString()
  33. .padStart(2, '0');
  34. const dd = Math.floor(second % 60)
  35. .toString()
  36. .padStart(2, '0');
  37. if (type === 'cn') {
  38. return mm + '分' + dd + '秒';
  39. } else {
  40. return mm + ':' + dd;
  41. }
  42. };
  43. export default defineComponent({
  44. name: 'video-play',
  45. props: {
  46. item: {
  47. type: Object,
  48. default: () => {
  49. return {};
  50. }
  51. },
  52. isEmtry: {
  53. type: Boolean,
  54. default: false
  55. },
  56. isActive: {
  57. type: Boolean,
  58. default: false
  59. },
  60. activeModel: {
  61. type: Boolean,
  62. default: true
  63. }
  64. },
  65. emits: [
  66. 'loadedmetadata',
  67. 'togglePlay',
  68. 'ended',
  69. 'reset',
  70. 'error',
  71. 'close',
  72. 'play',
  73. 'pause',
  74. 'seeked',
  75. 'seeking',
  76. 'waiting',
  77. 'timeupdate'
  78. ],
  79. setup(props, { emit, expose }) {
  80. const { item } = toRefs(props);
  81. const data = reactive({
  82. timer: null as any,
  83. currentTime: 0,
  84. duration: 0.1,
  85. loop: false,
  86. playState: 'pause' as 'play' | 'pause',
  87. vudio: null as any,
  88. showBar: true,
  89. speedControl: false,
  90. speedStyle: {
  91. left: '1px'
  92. },
  93. defaultSpeed: 1 // 默认速度
  94. });
  95. const speedBtnId = 'speed' + Date.now() + Math.floor(Math.random() * 100);
  96. /** 设置播放容器 16:9 */
  97. const parentContainer = reactive({
  98. width: '100%'
  99. });
  100. const setContainer = () => {
  101. const min = Math.min(screen.width, screen.height);
  102. const max = Math.max(screen.width, screen.height);
  103. const width = min * (16 / 9);
  104. if (width > max) {
  105. parentContainer.width = '100%';
  106. return;
  107. } else {
  108. parentContainer.width = width + 'px';
  109. }
  110. };
  111. // const forms = reactive({
  112. // subjectIds: [],
  113. // orgainIds: []
  114. // });
  115. const videoRef = ref();
  116. const videoItem = ref();
  117. const videoID = 'video' + Date.now() + Math.floor(Math.random() * 100);
  118. const toggleHideControl = (isShow: boolean) => {
  119. data.speedControl = false;
  120. data.showBar = isShow;
  121. };
  122. // const togglePlay = (e: Event) => {
  123. // e.stopPropagation()
  124. // }
  125. let playTimer = null as any;
  126. // 切换音频播放
  127. const onToggleAudio = (state: 'play' | 'pause') => {
  128. // console.log(state, 'state')
  129. data.speedControl = false;
  130. clearTimeout(playTimer);
  131. if (state === 'play') {
  132. playTimer = setTimeout(() => {
  133. videoItem.value?.play();
  134. data.playState = 'play';
  135. }, 100);
  136. } else {
  137. videoItem.value?.pause();
  138. data.playState = 'pause';
  139. }
  140. emit('togglePlay', data.playState);
  141. };
  142. const toggleLoop = () => {
  143. data.speedControl = false;
  144. if (!videoItem.value) return;
  145. if (data.loop) {
  146. videoItem.value.loop(false);
  147. showToast("已关闭循环播放")
  148. } else {
  149. videoItem.value.loop(true);
  150. showToast("已打开循环播放")
  151. }
  152. data.loop = !data.loop;
  153. };
  154. const changePlayBtn = (code: string) => {
  155. // data.speedControl = false;
  156. if (code == 'play') {
  157. data.playState = 'play';
  158. } else {
  159. data.playState = 'pause';
  160. }
  161. };
  162. /** 改变播放时间 */
  163. const handleChangeTime = (val: number) => {
  164. data.currentTime = val;
  165. clearTimeout(data.timer);
  166. data.timer = setTimeout(() => {
  167. videoItem.value.currentTime(val);
  168. data.timer = null;
  169. }, 300);
  170. };
  171. const __initVideo = () => {
  172. if (videoItem.value && props.item.id) {
  173. console.log(videoItem.value, 'videoItem.value');
  174. nextTick(() => {
  175. videoItem.value?.currentTime(0);
  176. });
  177. videoItem.value.poster(props.item.coverImg); // 封面
  178. videoItem.value.src(props.item.content); // url 播放地址
  179. videoItem.value.playbackRate(data.defaultSpeed);
  180. data.speedControl = false;
  181. // 初步加载时
  182. videoItem.value.on('loadedmetadata', () => {
  183. videoItem.value.playbackRate(data.defaultSpeed);
  184. // 获取时长
  185. data.duration = videoItem.value.duration();
  186. // 必须在当前元素
  187. if (item.value.autoPlay && videoItem.value && props.isActive) {
  188. // videoItem.value?.play()
  189. nextTick(() => {
  190. videoItem.value.currentTime(0);
  191. nextTick(handlePlayVideo);
  192. });
  193. }
  194. emit('loadedmetadata', videoItem.value);
  195. });
  196. // 视频播放时加载
  197. videoItem.value.on('timeupdate', () => {
  198. if (data.timer) return;
  199. data.currentTime = videoItem.value.currentTime();
  200. emit('timeupdate');
  201. });
  202. // 视频播放结束
  203. videoItem.value.on('ended', () => {
  204. changePlayBtn('pause');
  205. emit('ended');
  206. });
  207. //
  208. videoItem.value.on('pause', () => {
  209. data.playState = 'pause';
  210. changePlayBtn('pause');
  211. emit('togglePlay', true);
  212. emit('pause');
  213. });
  214. videoItem.value.on('seeked', () => {
  215. emit('seeked');
  216. });
  217. videoItem.value.on('seeking', () => {
  218. emit('seeking');
  219. });
  220. videoItem.value.on('waiting', () => {
  221. emit('waiting');
  222. });
  223. videoItem.value.on('play', () => {
  224. // console.log(play, 'playing')
  225. changePlayBtn('play');
  226. if (videoItem.value) {
  227. videoItem.value.muted(false);
  228. videoItem.value.volume(1);
  229. }
  230. // if (
  231. // !item.value.autoPlay &&
  232. // !item.value.isprepare &&
  233. // videoItem.value
  234. // ) {
  235. // // 加载完成后,取消静音播放
  236. // videoItem.value.pause();
  237. // }
  238. emit('togglePlay', videoItem.value?.paused);
  239. emit('play');
  240. });
  241. // 视频播放异常
  242. videoItem.value.on('error', (e: any) => {
  243. handleErrorVideo();
  244. emit('error');
  245. console.log(e, 'error');
  246. });
  247. }
  248. };
  249. let videoTimer = null as any;
  250. let videoTimerErrorCount = 0;
  251. const handlePlayVideo = () => {
  252. if (videoTimerErrorCount > 5) {
  253. return;
  254. }
  255. clearTimeout(videoTimer);
  256. nextTick(() => {
  257. videoItem.value?.play().catch((err: any) => {
  258. // console.log('🚀 ~ err:', err)
  259. videoTimer = setTimeout(() => {
  260. if (err?.message?.includes('play()')) {
  261. emit('play');
  262. }
  263. handlePlayVideo();
  264. }, 1000);
  265. });
  266. });
  267. videoTimerErrorCount++;
  268. };
  269. let videoErrorTimer = null as any;
  270. let videoErrorCount = 0;
  271. const handleErrorVideo = () => {
  272. if (videoErrorCount > 5) {
  273. return;
  274. }
  275. clearTimeout(videoErrorTimer);
  276. nextTick(() => {
  277. videoErrorTimer = setTimeout(() => {
  278. videoItem.value.src(props.item?.content);
  279. emit('play');
  280. videoItem.value.load();
  281. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  282. handleErrorVideo();
  283. }, 1000);
  284. });
  285. videoErrorCount++;
  286. };
  287. onMounted(() => {
  288. setContainer()
  289. videoItem.value = TCPlayer(videoID, {
  290. appID: '',
  291. controls: false,
  292. autoplay: true
  293. }); // player-container-id 为播放器容器 ID,必须与 html 中一致
  294. __initVideo();
  295. document.getElementById(speedBtnId)?.addEventListener('click', e => {
  296. e.stopPropagation();
  297. data.speedControl = !data.speedControl;
  298. });
  299. });
  300. watch(
  301. () => props.activeModel,
  302. () => {
  303. toggleHideControl(props.activeModel);
  304. }
  305. );
  306. watch(
  307. () => props.item,
  308. () => {
  309. videoItem.value?.currentTime(0);
  310. setTimeout(() => {
  311. videoItem.value?.pause();
  312. __initVideo();
  313. }, 60);
  314. }
  315. );
  316. // 去云练习完整版
  317. const gotoAccomany = (e: any) => {
  318. // 去云练习完整版
  319. e.stopPropagation();
  320. // 判断是否需要购买
  321. if(item.value.isLock) {
  322. handleShowVip(item.value.materialMusicId, "MUSIC")
  323. onToggleAudio("pause")
  324. return
  325. }
  326. // const Authorization = sessionStorage.getItem('Authorization') || '';
  327. // const origin = /(localhost|192)/.test(location.host)
  328. // ? 'https://test.gym.lexiaoya.cn'
  329. // : location.origin;
  330. // const src = `${origin}/${
  331. // state.platformType === 'TEACHER' ? 'accompany-teacher' : 'accompany'
  332. // }/#/detail/${
  333. // item.value.materialMusicId
  334. // }?Authorization=${Authorization}&isHideTitle=true`;
  335. const origin = /(localhost|192)/.test(location.host)
  336. ? 'https://test.gym.lexiaoya.cn/'
  337. : location.origin;
  338. const src = `${origin}/gym-music-score/?id=${item.value.materialMusicId}&isHideMusicList=true&systemType=${ state.platformType === 'TEACHER' ? 'teacher' : 'student'}`
  339. postMessage({
  340. api: 'openAccompanyWebView',
  341. content: {
  342. url: src,
  343. orientation: 0,
  344. c_orientation: 0,
  345. isHideTitle: true,
  346. statusBarTextColor: false,
  347. isOpenLight: true
  348. }
  349. });
  350. };
  351. const getVideoRef = () => {
  352. return videoRef.value;
  353. };
  354. const getPlyrRef = () => {
  355. return videoItem.value;
  356. };
  357. expose({
  358. changePlayBtn,
  359. toggleHideControl,
  360. getVideoRef,
  361. getPlyrRef
  362. });
  363. watch(
  364. () => props.isActive,
  365. val => {
  366. if (!val) {
  367. videoItem.value?.pause();
  368. }
  369. }
  370. );
  371. return () => (
  372. <div
  373. class={styles.videoWrap}
  374. onClick={() => {
  375. data.speedControl = false;
  376. }}>
  377. <div style={{ width: parentContainer.width, height: '100%', margin: '0 auto' }}>
  378. <video
  379. style={{ width: '100%', height: '100%' }}
  380. src={item.value.content}
  381. ref={videoRef}
  382. id={videoID}
  383. preload="auto"
  384. playsinline
  385. webkit-playsinline></video>
  386. <div class={styles.videoSection}></div>
  387. </div>
  388. <div
  389. class={[styles.controls, data.showBar ? '' : styles.hide]}
  390. onClick={(e: Event) => {
  391. e.stopPropagation();
  392. }}
  393. // onTouchmove={(e: TouchEvent) => {
  394. // emit('close')
  395. // }}
  396. >
  397. <div class={styles.slider}>
  398. <div class={styles.time}>
  399. <div>{getSecondRPM(data.currentTime)}</div>/
  400. <div>{getSecondRPM(data.duration)}</div>
  401. </div>
  402. <Slider
  403. step={0.01}
  404. class={styles.timeProgress}
  405. v-model={data.currentTime}
  406. max={data.duration}
  407. onUpdate:modelValue={val => {
  408. handleChangeTime(val);
  409. }}
  410. />
  411. </div>
  412. <div class={styles.actionSection}>
  413. <div class={styles.actions} onClick={() => emit('close')}>
  414. <div
  415. class={styles.actionBtn}
  416. onClick={(e: any) => {
  417. e.stopPropagation();
  418. onToggleAudio(data.playState === 'pause' ? 'play' : 'pause');
  419. }}>
  420. <img src={data.playState === 'pause' ? iconPlay : iconPause} />
  421. </div>
  422. <div class={[styles.actionBtn, styles.btnLoop]} onClick={toggleLoop}>
  423. <img src={data.loop ? iconLoopActive : iconLoop} />
  424. </div>
  425. <div class={styles.actionBtn} id={speedBtnId}>
  426. <img src={iconSpeed} />
  427. </div>
  428. </div>
  429. {/* <div class={styles.name}>{item.value.name}</div> */}
  430. {item.value.materialMusicId && (
  431. <div
  432. class={[styles.goPractice]}
  433. onClick={gotoAccomany}></div>
  434. )}
  435. </div>
  436. </div>
  437. <div
  438. style={{
  439. display: data.speedControl ? 'block' : 'none'
  440. }}>
  441. <div
  442. class={styles.sliderPopup}
  443. onClick={(e: Event) => {
  444. e.stopPropagation();
  445. }}>
  446. <i
  447. class={styles.iconAdd}
  448. onClick={() => {
  449. if (data.defaultSpeed >= 1.5) {
  450. return;
  451. }
  452. if (videoItem.value) {
  453. data.defaultSpeed = (data.defaultSpeed * 10 + 1) / 10;
  454. videoItem.value.playbackRate(data.defaultSpeed);
  455. }
  456. }}></i>
  457. <Slider
  458. min={0.5}
  459. max={1.5}
  460. step={0.1}
  461. v-model={data.defaultSpeed}
  462. vertical
  463. barHeight={5}
  464. reverse
  465. onChange={() => {
  466. if (videoItem.value) {
  467. videoItem.value.playbackRate(data.defaultSpeed);
  468. }
  469. }}>
  470. {{
  471. button: () => (
  472. <div class={styles.sliderPoint}>
  473. {data.defaultSpeed}
  474. <span>x</span>
  475. </div>
  476. )
  477. }}
  478. </Slider>
  479. <i
  480. class={[styles.iconCut]}
  481. onClick={() => {
  482. if (data.defaultSpeed <= 0.5) {
  483. return;
  484. }
  485. if (videoItem.value) {
  486. data.defaultSpeed = (data.defaultSpeed * 10 - 1) / 10;
  487. videoItem.value.playbackRate(data.defaultSpeed);
  488. }
  489. }}></i>
  490. </div>
  491. </div>
  492. </div>
  493. );
  494. }
  495. });