index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. import { defineComponent, onMounted, reactive, ref, onUnmounted, watch } from 'vue';
  2. import { useRoute, useRouter } from 'vue-router';
  3. import { browser, vaildMusicScoreUrl } from "@/helpers/utils"
  4. import styles from './index.module.less';
  5. import "plyr/dist/plyr.css";
  6. import Plyr from "plyr";
  7. import { Vue3Lottie } from "vue3-lottie";
  8. import audioBga from "../images/audioBga.json";
  9. import videobg from "../images/videobg.png";
  10. import backImg from "../images/back.png";
  11. import {
  12. postMessage
  13. } from '@/helpers/native-message';
  14. import { usePageVisibility } from '@vant/use';
  15. export default defineComponent({
  16. name: 'playCreation',
  17. setup() {
  18. const {isApp} = browser()
  19. const route = useRoute();
  20. const router = useRouter();
  21. const resourceUrl = decodeURIComponent(route.query.resourceUrl as string || '');
  22. const musicSheetName = decodeURIComponent(route.query.musicSheetName as string || '');
  23. const username = decodeURIComponent(route.query.username as string || '');
  24. const musicSheetId = decodeURIComponent(route.query.musicSheetId as string || '');
  25. const videoBgUrl = decodeURIComponent(route.query.videoBgUrl as string || '');
  26. const playType = resourceUrl.lastIndexOf('mp4') !== -1 ? 'Video' : 'Audio'
  27. const lottieDom = ref()
  28. const landscapeScreen = ref(false)
  29. let _plrl:any
  30. const playIngShow = ref(true)
  31. const loaded = ref(false)
  32. let isInitAudioVisualDraw = false
  33. const { registerDrag, unRegisterDrag } = landscapeScreenDrag()
  34. watch(landscapeScreen, ()=>{
  35. if(landscapeScreen.value){
  36. registerDrag()
  37. }else{
  38. unRegisterDrag()
  39. }
  40. })
  41. // 谱面
  42. const staffState = reactive({
  43. staffSrc: "",
  44. isShow: false,
  45. height:"initial",
  46. speedRate:Number(decodeURIComponent(route.query.speedRate as string || "1")),
  47. musicRenderType:decodeURIComponent(route.query.musicRenderType as string || "staff"),
  48. partIndex:Number(decodeURIComponent(route.query.partIndex as string || "0"))
  49. })
  50. const staffDom= ref<HTMLIFrameElement>()
  51. const {playStaff, pauseStaff, updateProgressStaff} = staffMoveInstance()
  52. function initPlay(){
  53. const id = playType === "Audio" ? "#audioMediaSrc" : "#videoMediaSrc";
  54. _plrl = new Plyr(id, {
  55. controls: ["play", "progress", "current-time", "duration"]
  56. });
  57. // 在微信中运行的时候,微信没有开放自动加载资源的权限,所以要等播放之后才显示播放控制器
  58. _plrl.on('loadedmetadata', () => {
  59. loaded.value = true
  60. });
  61. _plrl.on('play', () => {
  62. playIngShow.value = false
  63. playStaff()
  64. });
  65. _plrl.on('pause', () => {
  66. playIngShow.value = true
  67. pauseStaff()
  68. });
  69. _plrl.on('seeked', () => {
  70. // 暂停的时候调用
  71. if(!_plrl.playing){
  72. updateProgressStaff(_plrl.currentTime)
  73. }
  74. });
  75. }
  76. // 注册 横屏时候的自定义拖动事件 解决旋转时候拖动进度条坐标的问题
  77. function landscapeScreenDrag() {
  78. let progressBar: HTMLElement
  79. function onDown(e: MouseEvent | TouchEvent) {
  80. e.preventDefault();
  81. e.stopPropagation();
  82. // 记录拖动之前的状态
  83. const playing = _plrl.playing
  84. _plrl.pause()
  85. const isTouchEv = isTouchEvent(e);
  86. const event = isTouchEv ? e.touches[0] : e;
  87. setProgress(event)
  88. function onUp() {
  89. document.removeEventListener(
  90. isTouchEv ? 'touchmove' : 'mousemove',
  91. onMove
  92. );
  93. document.removeEventListener(isTouchEv ? 'touchend' : 'mouseup', onUp);
  94. playing && _plrl.play() // 之前是播放状态 就播放
  95. }
  96. function onMove(e: MouseEvent | TouchEvent){
  97. e.preventDefault();
  98. e.stopPropagation();
  99. const event = isTouchEvent(e) ? e.touches[0] : e;
  100. setProgress(event)
  101. }
  102. function setProgress(event: MouseEvent | Touch) {
  103. const {top, height} = progressBar.getBoundingClientRect();
  104. const progress = (event.clientY - top) / height;
  105. const progressNum = Math.min(Math.max(progress, 0), 1);
  106. _plrl.currentTime = progressNum * _plrl.duration
  107. }
  108. document.addEventListener(isTouchEv ? 'touchmove' : 'mousemove', onMove);
  109. document.addEventListener(isTouchEv ? 'touchend' : 'mouseup', onUp);
  110. }
  111. function registerDrag() {
  112. if(!progressBar){
  113. progressBar = document.querySelector('#landscapeScreenPlay .plyr__progress__container') as HTMLElement;
  114. }
  115. progressBar.addEventListener('mousedown', onDown);
  116. progressBar.addEventListener('touchstart', onDown);
  117. }
  118. function unRegisterDrag() {
  119. progressBar.removeEventListener('mousedown', onDown);
  120. progressBar.removeEventListener('touchstart', onDown);
  121. }
  122. return {
  123. registerDrag,
  124. unRegisterDrag
  125. }
  126. }
  127. function isTouchEvent(e: MouseEvent | TouchEvent): e is TouchEvent {
  128. return window.TouchEvent && e instanceof window.TouchEvent;
  129. }
  130. /**
  131. * 音频可视化
  132. * @param audioDom
  133. * @param canvasDom
  134. * @param fftSize 2的幂数,最小为32
  135. */
  136. function audioVisualDraw(audioDom: HTMLAudioElement, canvasDom: HTMLCanvasElement, fftSize = 128) {
  137. type propsType = { canvWidth: number; canvHeight: number; canvFillColor: string; lineColor: string; lineGap: number }
  138. // canvas
  139. const canvasCtx = canvasDom.getContext("2d")!
  140. let { width, height } = canvasDom.getBoundingClientRect()
  141. // 这里横屏的时候需要旋转,所以宽高变化一下
  142. if(landscapeScreen.value){
  143. const _width = width
  144. width = height
  145. height = _width
  146. }
  147. canvasDom.width = width
  148. canvasDom.height = height
  149. // audio
  150. const audioCtx = new AudioContext()
  151. const source = audioCtx.createMediaElementSource(audioDom)
  152. const analyser = audioCtx.createAnalyser()
  153. analyser.fftSize = fftSize
  154. source?.connect(analyser)
  155. analyser.connect(audioCtx.destination)
  156. const dataArray = new Uint8Array(fftSize / 2)
  157. const draw = (data: Uint8Array, ctx: CanvasRenderingContext2D, { lineGap, canvWidth, canvHeight, canvFillColor, lineColor }: propsType) => {
  158. if (!ctx) return
  159. const w = canvWidth
  160. const h = canvHeight
  161. fillCanvasBackground(ctx, w, h, canvFillColor)
  162. // 可视化
  163. const dataLen = data.length
  164. let step = (w / 2 - lineGap * dataLen) / dataLen
  165. step < 1 && (step = 1)
  166. const midX = w / 2
  167. const midY = h / 2
  168. let xLeft = midX
  169. for (let i = 0; i < dataLen; i++) {
  170. const value = data[i]
  171. const percent = value / 255 // 最大值为255
  172. const barHeight = percent * midY
  173. canvasCtx.fillStyle = lineColor
  174. // 中间加间隙
  175. if (i === 0) {
  176. xLeft -= lineGap / 2
  177. }
  178. canvasCtx.fillRect(xLeft - step, midY - barHeight, step, barHeight)
  179. canvasCtx.fillRect(xLeft - step, midY, step, barHeight)
  180. xLeft -= step + lineGap
  181. }
  182. let xRight = midX
  183. for (let i = 0; i < dataLen; i++) {
  184. const value = data[i]
  185. const percent = value / 255 // 最大值为255
  186. const barHeight = percent * midY
  187. canvasCtx.fillStyle = lineColor
  188. if (i === 0) {
  189. xRight += lineGap / 2
  190. }
  191. canvasCtx.fillRect(xRight, midY - barHeight, step, barHeight)
  192. canvasCtx.fillRect(xRight, midY, step, barHeight)
  193. xRight += step + lineGap
  194. }
  195. }
  196. const fillCanvasBackground = (ctx: CanvasRenderingContext2D, w: number, h: number, colors: string) => {
  197. ctx.clearRect(0, 0, w, h)
  198. ctx.fillStyle = colors
  199. ctx.fillRect(0, 0, w, h)
  200. }
  201. const requestAnimationFrameFun = () => {
  202. requestAnimationFrame(() => {
  203. analyser?.getByteFrequencyData(dataArray)
  204. draw(dataArray, canvasCtx, {
  205. lineGap: 2,
  206. canvWidth: width,
  207. canvHeight: height,
  208. canvFillColor: "transparent",
  209. lineColor: "rgba(255, 255, 255, 0.7)"
  210. })
  211. if (!isPause) {
  212. requestAnimationFrameFun()
  213. }
  214. })
  215. }
  216. let isPause = true
  217. const playVisualDraw = () => {
  218. //audioCtx.resume() // 重新更新状态 加了暂停和恢复音频音质发生了变化 所以这里取消了
  219. isPause = false
  220. requestAnimationFrameFun()
  221. }
  222. const pauseVisualDraw = () => {
  223. isPause = true
  224. //audioCtx?.suspend() // 暂停 加了暂停和恢复音频音质发生了变化 所以这里取消了
  225. // source?.disconnect()
  226. // analyser?.disconnect()
  227. }
  228. return {
  229. playVisualDraw,
  230. pauseVisualDraw
  231. }
  232. }
  233. function handlerBack(event:MouseEvent){
  234. event.stopPropagation()
  235. router.back()
  236. }
  237. //点击改变播放状态
  238. function handlerClickPlay(event:MouseEvent){
  239. //由于ios低版本必须在用户操作之后才能初始化 createMediaElementSource 所以必须在用户操作之后初始化
  240. if(!isInitAudioVisualDraw && playType === "Audio"){
  241. isInitAudioVisualDraw = true
  242. // 创建音波数据
  243. const audioDom = document.querySelector("#audioMediaSrc") as HTMLAudioElement
  244. const canvasDom = document.querySelector("#audioVisualizer") as HTMLCanvasElement
  245. const { pauseVisualDraw, playVisualDraw } = audioVisualDraw(audioDom, canvasDom)
  246. _plrl.on('play', () => {
  247. lottieDom.value.play()
  248. playVisualDraw()
  249. });
  250. _plrl.on('pause', () => {
  251. lottieDom.value.pause()
  252. pauseVisualDraw()
  253. });
  254. }
  255. // 原生 播放暂停按钮 点击的时候 不触发
  256. // @ts-ignore
  257. if(event.target?.matches('button.plyr__control')){
  258. return
  259. }
  260. if (_plrl.playing) {
  261. _plrl.pause();
  262. } else {
  263. _plrl.play();
  264. }
  265. }
  266. function handlerLandscapeScreen(){
  267. // app端调用app的横屏
  268. if(isApp){
  269. postMessage({
  270. api: "setRequestedOrientation",
  271. content: {
  272. orientation: 0,
  273. },
  274. });
  275. }else{
  276. // web端使用旋转的方式
  277. updateLandscapeScreenState()
  278. window.addEventListener('resize', updateLandscapeScreenState)
  279. }
  280. }
  281. function updateLandscapeScreenState(){
  282. // 下一帧 计算 横竖屏切换太快 获取的宽高不准
  283. requestAnimationFrame(()=>{
  284. if(window.innerWidth > window.innerHeight){
  285. landscapeScreen.value = false
  286. }else{
  287. landscapeScreen.value = true
  288. }
  289. })
  290. }
  291. const pageVisibility = usePageVisibility();
  292. watch(pageVisibility, value => {
  293. if (value === 'hidden') {
  294. _plrl?.pause();
  295. }
  296. });
  297. // 初始化五线谱
  298. function initStaff(){
  299. const src = `${vaildMusicScoreUrl()}/instrument/#/simple-detail?id=${musicSheetId}&musicRenderType=${staffState.musicRenderType}&part-index=${staffState.partIndex}`;
  300. //const src = `https://dev.kt.colexiu.com/instrument/#/simple-detail?id=${musicSheetId}&musicRenderType=${staffState.musicRenderType}&part-index=${staffState.partIndex}`;
  301. staffState.staffSrc = src
  302. window.addEventListener('message', (event) => {
  303. const { api, height } = event.data;
  304. if (api === 'api_musicPage') {
  305. staffState.isShow = true
  306. staffState.height = height + "px"
  307. // 如果是播放中自动开始 播放
  308. if(_plrl.playing){
  309. playStaff()
  310. }
  311. }
  312. });
  313. }
  314. function staffMoveInstance(){
  315. let isPause = true
  316. const requestAnimationFrameFun = () => {
  317. requestAnimationFrame(() => {
  318. staffDom.value?.contentWindow?.postMessage(
  319. {
  320. api: 'api_playProgress',
  321. content: {
  322. currentTime: _plrl.currentTime * staffState.speedRate
  323. }
  324. },
  325. "*"
  326. )
  327. if (!isPause) {
  328. requestAnimationFrameFun()
  329. }
  330. })
  331. }
  332. const playStaff = () => {
  333. // 没渲染不执行
  334. if(!staffState.isShow) return
  335. isPause = false
  336. staffDom.value?.contentWindow?.postMessage(
  337. {
  338. api: 'api_play'
  339. },
  340. "*"
  341. )
  342. requestAnimationFrameFun()
  343. }
  344. const pauseStaff = () => {
  345. // 没渲染不执行
  346. if(!staffState.isShow) return
  347. isPause = true
  348. staffDom.value?.contentWindow?.postMessage(
  349. {
  350. api: 'api_paused'
  351. },
  352. "*"
  353. )
  354. }
  355. const updateProgressStaff = (currentTime: number) => {
  356. // 没渲染不执行
  357. if(!staffState.isShow) return
  358. staffDom.value?.contentWindow?.postMessage(
  359. {
  360. api: 'api_updateProgress',
  361. content: {
  362. currentTime: currentTime * staffState.speedRate
  363. }
  364. },
  365. "*"
  366. )
  367. }
  368. return {
  369. playStaff,
  370. pauseStaff,
  371. updateProgressStaff
  372. }
  373. }
  374. onMounted(()=>{
  375. // 五线谱
  376. initStaff()
  377. initPlay()
  378. handlerLandscapeScreen()
  379. })
  380. onUnmounted(()=>{
  381. if(isApp){
  382. postMessage({
  383. api: "setRequestedOrientation",
  384. content: {
  385. orientation: 1,
  386. },
  387. });
  388. }else{
  389. window.removeEventListener('resize', updateLandscapeScreenState)
  390. }
  391. })
  392. return () =>
  393. <div id="landscapeScreenPlay" class={[styles.playCreation,landscapeScreen.value && styles.landscapeScreen,!loaded.value && styles.notLoaded]} onClick={handlerClickPlay}>
  394. <div class={styles.backBox}>
  395. <img class={styles.backImg} src={backImg} onClick={handlerBack} />
  396. <div class={styles.musicDetail}>
  397. <div class={styles.musicSheetName}>{musicSheetName}</div>
  398. <div class={styles.username}>{username}</div>
  399. </div>
  400. </div>
  401. {
  402. playType === 'Audio' ?
  403. <div class={styles.audioBox}>
  404. <canvas class={styles.audioVisualizer} id="audioVisualizer"></canvas>
  405. <Vue3Lottie ref={lottieDom} class={styles.audioBga} animationData={audioBga} autoPlay={false} loop={true}></Vue3Lottie>
  406. <audio
  407. crossorigin="anonymous"
  408. id="audioMediaSrc"
  409. src={resourceUrl}
  410. controls="false"
  411. preload="metadata"
  412. playsinline
  413. />
  414. </div>
  415. :
  416. <video
  417. id="videoMediaSrc"
  418. class={styles.videoBox}
  419. src={resourceUrl}
  420. data-poster={ videoBgUrl || videobg}
  421. preload="metadata"
  422. playsinline
  423. />
  424. }
  425. <div class={[styles.playLarge, playIngShow.value && styles.playIngShow]}></div>
  426. {/* 谱面 */}
  427. {
  428. staffState.staffSrc &&
  429. <div
  430. class={[styles.staffBox, staffState.isShow && styles.staffBoxShow]}
  431. style={
  432. {
  433. '--staffBoxHeight':staffState.height
  434. }
  435. }
  436. >
  437. <div class={styles.mask}></div>
  438. <iframe
  439. ref={staffDom}
  440. class={styles.staff}
  441. frameborder="0"
  442. src={staffState.staffSrc}>
  443. </iframe>
  444. </div>
  445. }
  446. </div>;
  447. }
  448. });