index.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. import styles from "./index.module.less";
  2. import { Snackbar } from "@varlet/ui";
  3. import { closeToast, showLoadingToast, showToast, Popup } from "vant";
  4. import { defineComponent, onMounted, onUnmounted, reactive, ref, watch } from "vue";
  5. import { getLeveByScore, getLeveByScoreMeasure, IEvaluatings } from "./evaluatResult";
  6. import {
  7. cancelEvaluating,
  8. endEvaluating,
  9. endSoundCheck,
  10. getEarphone,
  11. api_proxyServiceMessage,
  12. removeResult,
  13. sendResult,
  14. startEvaluating,
  15. startSoundCheck,
  16. api_openWebView,
  17. api_startRecording,
  18. api_startRecordingCb,
  19. api_stopRecording,
  20. api_recordStartTime,
  21. api_remove_recordStartTime,
  22. api_startCapture,
  23. api_endCapture,
  24. api_getDeviceDelay,
  25. hideComplexButton,
  26. api_checkSocketStatus,
  27. addAccompanyError,
  28. removeAccompanyError,
  29. addSocketStatus,
  30. removeSocketStatus,
  31. api_disconnectSocket,
  32. api_midiMicDelay,
  33. api_cloudSetCurrentTime,
  34. api_cloudChangeSpeed,
  35. api_startDelayCheck,
  36. api_closeDelayCheck,
  37. } from "/src/helpers/communication";
  38. import state, { IPlayState, clearSelection, handleStopPlay, onPlay, resetPlaybackToStart, togglePlay, initSetPlayRate } from "/src/state";
  39. import { IPostMessage } from "/src/utils/native-message";
  40. import { usePageVisibility } from "@vant/use";
  41. import { browser } from "/src/utils";
  42. import { getAudioCurrentTime, toggleMutePlayAudio, audioListStart, audioData } from "../audio-list";
  43. import { handleStartTick, closeTick } from "../tick";
  44. import AbnormalPop from "../abnormal-pop";
  45. import { storeData } from "../../store";
  46. import icon_bg from "../abnormal-pop/icon_bg.svg";
  47. import icon_close from "../abnormal-pop/icon_close.svg";
  48. import icon_btn from "../abnormal-pop/icon_btn.svg";
  49. import icon_success from "../abnormal-pop/icon_success.svg";
  50. import { data } from "../../page-instrument/custom-plugins/work-index";
  51. import { startCountdown } from "/src/page-instrument/evaluat-model/countdown";
  52. const browserInfo = browser();
  53. let socketStartTime = 0;
  54. export const popImgs = {
  55. icon_bg,
  56. icon_close,
  57. icon_btn,
  58. icon_success,
  59. };
  60. export const evaluatingData = reactive({
  61. /** 评测数据 */
  62. contentData: {} as any,
  63. /** 评测模块是否加载完成 */
  64. rendered: false,
  65. earphone: false, // 是否插入耳机
  66. soundEffect: false, // 是否效音
  67. soundEffectFrequency: 0, // 效音频率
  68. checkStep: 0, // 执行步骤
  69. checkEnd: false, // 检测结束
  70. earphoneMode: false, // 耳机弹窗
  71. earPhoneType: "" as "" | "有线耳机" | "蓝牙耳机", // 耳机类型
  72. soundEffectMode: false, // 效音弹窗
  73. websocketState: false, // websocket连接状态
  74. /**是否开始播放 */
  75. startBegin: false, // 开始
  76. backtime: 0, // 延迟时间
  77. /** 已经评测的数据 */
  78. evaluatings: {} as IEvaluatings,
  79. /** 评测结果 */
  80. resultData: {} as any,
  81. /** 评测结果弹窗 */
  82. resulstMode: false,
  83. /** 是否是完整评测 */
  84. isComplete: false,
  85. /** */
  86. isDisabledPlayMusic: false,
  87. /** socket异常状态弹窗 */
  88. socketErrorPop: false,
  89. /** 异常提示 */
  90. errorContents: '',
  91. /** socket异常状态弹窗的状态值 */
  92. socketErrorStatus: 0,
  93. /** 延迟检测,socket状态异常 */
  94. delayCheckSocketError: false,
  95. /** 异常状态,不生成评测记录,不调用保存接口 */
  96. isErrorState: false,
  97. /** accompanyError,错误类型 */
  98. accompanyErrorType: '',
  99. /** app播放结束状态,重新评测需要重置为 */
  100. isAudioPlayEnd: false,
  101. preloadJson: true, // 预加载延迟检测的资源
  102. jsonLoading: true, // 延迟检测的资源加载中状态
  103. jsonLoadDone: true, // 延迟检测的动画dom加载完成状态
  104. hideResultModal: false, // 评测作业,如果不是完整评测,需要隐藏评测结果弹窗
  105. oneselfCancleEvaluating: false, // 是否是自主取消评测,自主取消评测,不生产评测记录
  106. isBeginMask: false // 倒计时和系统节拍器时候的遮罩,防止用户点击
  107. });
  108. const sendOffsetTime = async (offsetTime: number) => {
  109. const delayData = await api_getDeviceDelay();
  110. api_midiMicDelay({
  111. header: {
  112. commond: "audioPlayStart",
  113. type: "SOUND_COMPARE",
  114. },
  115. body: {
  116. offsetTime,
  117. micDelay: delayData?.content?.value,
  118. },
  119. });
  120. };
  121. /** 点击开始评测按钮 */
  122. export const handleStartEvaluat = async () => {
  123. if (state.modeType === "evaluating") {
  124. handleCancelEvaluat();
  125. // 放下面会在异步之后执行 旋律线可能在会隐藏不了
  126. state.modeType = "practise";
  127. } else {
  128. // 放下面会在异步之后执行 旋律线可能在会隐藏不了
  129. state.modeType = "evaluating";
  130. if (state.platform !== "PC") {
  131. // 评测前先检查APP端的websocket状态
  132. const res = await api_checkSocketStatus();
  133. if (res?.content?.status === "connected") {
  134. handleStopPlay();
  135. } else {
  136. // socket未连接
  137. // evaluatingData.socketErrorPop = true
  138. }
  139. } else {
  140. handleStopPlay();
  141. }
  142. }
  143. //state.modeType = state.modeType === "evaluating" ? "practise" : "evaluating";
  144. if (state.modeType !== "evaluating") {
  145. // 切换到练习模式,卸载评测模块
  146. evaluatingData.rendered = false;
  147. }
  148. };
  149. /** 开始评测 & 延迟检测开始按钮 */
  150. export const startCheckDelay = async () => {
  151. // 评测前先检查APP端的websocket状态
  152. const res = await api_checkSocketStatus();
  153. if (res?.content?.status === "connected") {
  154. //
  155. return new Promise((resolve) => {
  156. resolve({ checked: true });
  157. });
  158. } else {
  159. /**
  160. * socket未连接,记录此时的时间,以便于和收到socket成功链接,进行对比,对比时间小于500ms时,则连接中的状态默认显示500ms持续时间
  161. *
  162. * */
  163. socketStartTime = +new Date();
  164. evaluatingData.socketErrorPop = true;
  165. evaluatingData.socketErrorStatus = 1;
  166. return new Promise((resolve) => {
  167. resolve({ checked: false });
  168. });
  169. }
  170. };
  171. const check_currentTime = () => {
  172. let preTime = 0;
  173. // 选段评测模式
  174. if (state.isSelectMeasureMode) {
  175. preTime = state.section[0].time * 1000;
  176. }
  177. const currentTime = getAudioCurrentTime() * 1000 - preTime;
  178. // console.log('播放进度music', currentTime, 'preTime:' + preTime)
  179. if (currentTime >= 500) {
  180. sendEvaluatingOffsetTime(500);
  181. return;
  182. }
  183. setTimeout(() => {
  184. check_currentTime();
  185. }, 10);
  186. };
  187. /** 开始播放发送延迟时间 */
  188. export const sendEvaluatingOffsetTime = async (currentTime: number) => {
  189. // 没有开始时间点, 不处理
  190. if (!evaluatingData.backtime) return;
  191. const nowTime = Date.now();
  192. const delayTime = nowTime - evaluatingData.backtime - currentTime;
  193. console.error("真正播放延迟", delayTime, "currentTime:", currentTime);
  194. await api_proxyServiceMessage({
  195. header: {
  196. commond: "audioPlayStart",
  197. type: "SOUND_COMPARE",
  198. },
  199. body: {
  200. offsetTime: delayTime < 0 ? 0 : delayTime,
  201. micDelay: 0,
  202. },
  203. });
  204. };
  205. /** 检测耳机 */
  206. export const checkUseEarphone = async () => {
  207. const res = await getEarphone();
  208. return res?.content?.checkIsWired || false;
  209. };
  210. /**
  211. * 开始录音
  212. */
  213. const handleStartSoundCheck = () => {
  214. startSoundCheck();
  215. };
  216. /** 结束录音 */
  217. export const handleEndSoundCheck = () => {
  218. endSoundCheck();
  219. };
  220. /** 连接websocket */
  221. export const connectWebsocket = async (content: any) => {
  222. evaluatingData.contentData = content;
  223. evaluatingData.websocketState = true;
  224. };
  225. /**
  226. * 执行检测
  227. */
  228. export const handlePerformDetection = async () => {
  229. // 检测完成不检测了
  230. if (evaluatingData.checkEnd) return;
  231. // 延迟检测
  232. if (evaluatingData.checkStep === 0) {
  233. evaluatingData.checkStep = 5;
  234. // 没有设备延迟数据 或 开启了效音 显示检测组件,并持续检测耳机状态
  235. if (state.setting.soundEffect) {
  236. evaluatingData.soundEffectMode = true;
  237. return;
  238. }
  239. const delayTime = await api_getDeviceDelay();
  240. console.log("🚀 ~ delayTime:", delayTime);
  241. if (!delayTime) {
  242. evaluatingData.soundEffectMode = true;
  243. return;
  244. }
  245. handlePerformDetection();
  246. return;
  247. }
  248. // 检测耳机
  249. if ((evaluatingData.checkStep = 5)) {
  250. evaluatingData.checkStep = 10;
  251. const erji = await checkUseEarphone();
  252. if (!erji) {
  253. evaluatingData.earphoneMode = true;
  254. return;
  255. }
  256. handlePerformDetection();
  257. return;
  258. }
  259. // 效音
  260. // if (evaluatingData.checkStep === 7) {
  261. // // 是否需要开启效音
  262. // evaluatingData.checkStep = 10;
  263. // if (state.setting.soundEffect && !state.isPercussion) {
  264. // evaluatingData.soundEffectMode = true;
  265. // handleStartSoundCheck();
  266. // return
  267. // }
  268. // handlePerformDetection();
  269. // return;
  270. // }
  271. // 效验完成
  272. if (evaluatingData.checkStep === 10) {
  273. evaluatingData.checkEnd = true;
  274. }
  275. };
  276. /** 记录小节分数 */
  277. export const addMeasureScore = (measureScore: any, show = true) => {
  278. // #8720 bug修复
  279. for (let idx in evaluatingData.evaluatings) {
  280. evaluatingData.evaluatings[idx].show = false;
  281. }
  282. evaluatingData.evaluatings[measureScore.measureRenderIndex] = {
  283. ...measureScore,
  284. leve: getLeveByScoreMeasure(measureScore.score),
  285. show,
  286. };
  287. // console.log("🚀 ~ measureScore:", evaluatingData.evaluatings)
  288. };
  289. const handleScoreResult = (res?: IPostMessage) => {
  290. console.log("返回", res, evaluatingData.oneselfCancleEvaluating);
  291. // 如果是手动取消评测,不生成评测记录
  292. if (evaluatingData.oneselfCancleEvaluating) {
  293. return;
  294. }
  295. if (res?.content) {
  296. const { header, body } = res.content;
  297. // 效音返回
  298. if (header.commond === "checking") {
  299. evaluatingData.soundEffectFrequency = body.frequency;
  300. }
  301. // 小节评分返回
  302. if (header?.commond === "measureScore") {
  303. console.log("🚀 ~ 评测返回:", res);
  304. addMeasureScore(body);
  305. }
  306. // 评测结束返回
  307. if (header?.commond === "overall") {
  308. console.log("🚀 ~ 评测返回:", res);
  309. console.log("评测结束", body);
  310. state.isHideEvaluatReportSaveBtn = false;
  311. setTimeout(() => {
  312. // 评测作业,如果不是完整评测,不展示评测弹窗
  313. if (data.trainingType === "EVALUATION" && !evaluatingData.isComplete) {
  314. evaluatingData.hideResultModal = true;
  315. } else {
  316. evaluatingData.hideResultModal = false;
  317. }
  318. evaluatingData.resulstMode = evaluatingData.isErrorState ? false : true;
  319. }, 200);
  320. evaluatingData.resultData = {
  321. ...body,
  322. ...getLeveByScore(body.score),
  323. };
  324. // console.log("🚀 ~ evaluatingData.resultData:", evaluatingData.resultData)
  325. closeToast();
  326. }
  327. }
  328. };
  329. /** 开始评测 */
  330. export const handleStartBegin = async (preTimes?: number) => {
  331. if (state.isAppPlay) {
  332. await api_cloudSetCurrentTime({
  333. currentTime: 0,
  334. songID: state.examSongId,
  335. })
  336. }
  337. evaluatingData.isComplete = false;
  338. evaluatingData.evaluatings = {};
  339. evaluatingData.resultData = {};
  340. evaluatingData.backtime = 0;
  341. evaluatingData.isAudioPlayEnd = false;
  342. const res = await startEvaluating(evaluatingData.contentData);
  343. if (res?.api !== "startEvaluating") {
  344. Snackbar.error("请在APP端进行评测");
  345. evaluatingData.startBegin = false;
  346. return;
  347. }
  348. if (res?.content?.reson) {
  349. showToast(res.content?.des);
  350. evaluatingData.startBegin = false;
  351. return;
  352. }
  353. initSetPlayRate();
  354. resetPlaybackToStart();
  355. evaluatingData.startBegin = true;
  356. if (evaluatingData.isDisabledPlayMusic) {
  357. evaluatingData.isBeginMask = true
  358. // 先播放倒计时
  359. await startCountdown()
  360. state.playState = state.playState === "paused" ? "play" : "paused";
  361. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  362. if (state.playState === "play" && (state.playType==="play"&&state.needTick)||(state.playType==="sing"&&state.needSingTick)) {
  363. // 如果是系统节拍器 等系统节拍器播完了再播,如果是mp3节拍器 直接播
  364. if((state.playType==="play" && !state.isOpenMetronome)||(state.playType==="sing" && !state.isSingOpenMetronome)){
  365. const tickend = await handleStartTick();
  366. console.log("🚀 ~ tickend:", tickend)
  367. // 节拍器返回false, 取消播放
  368. if (!tickend) {
  369. state.playState = "paused";
  370. evaluatingData.startBegin = false;
  371. evaluatingData.isBeginMask = false
  372. return;
  373. }
  374. }else{
  375. handleStartTick()
  376. }
  377. }
  378. evaluatingData.isBeginMask = false
  379. onPlay();
  380. }
  381. if (evaluatingData.isErrorState) return
  382. //开始录音
  383. // await api_startRecording({
  384. // accompanimentState: state.setting.enableAccompaniment ? 1 : 0,
  385. // firstNoteTime: preTimes || 0,
  386. // });
  387. let rate = state.speed / state.originSpeed;
  388. rate = parseFloat(rate.toFixed(2));
  389. await api_startRecordingCb({
  390. // accompanimentState: state.setting.enableAccompaniment ? 1 : 0,
  391. accompanimentState: !state.accompany ? 0 : 1, // 评测没有伴奏时,静音播放
  392. firstNoteTime: preTimes || 0,
  393. speedRate: rate, // 播放倍率
  394. }, () => {
  395. if (state.isAppPlay) {
  396. setTimeout(() => {
  397. sendOffsetTime(0)
  398. }, 300);
  399. }
  400. })
  401. // 如果开启了摄像头, 开启录制视频
  402. if (state.setting.camera) {
  403. console.log("开始录制视频");
  404. await api_startCapture();
  405. }
  406. // 如果是midi音频评测,需要调用cloudPlay
  407. if (state.isAppPlay) {
  408. await api_cloudChangeSpeed({
  409. speed: state.originSpeed,
  410. originalSpeed: state.originSpeed,
  411. songID: state.examSongId,
  412. });
  413. audioData.progress = 0
  414. audioListStart(state.playState);
  415. }
  416. evaluatingData.oneselfCancleEvaluating = false;
  417. };
  418. /** 播放音乐 */
  419. const playMusic = async () => {
  420. const playState = await togglePlay("play");
  421. // 取消播放,停止播放
  422. if (!playState) {
  423. evaluatingData.startBegin = false;
  424. handleCancelEvaluat();
  425. return;
  426. }
  427. // 检测播放进度, 计算延迟
  428. check_currentTime();
  429. // 如果开启了摄像头, 开启录制视频
  430. if (state.setting.camera) {
  431. console.log("开始录制视频");
  432. api_startCapture();
  433. }
  434. };
  435. let _audio: HTMLAudioElement;
  436. /** 录音开始,记录开始时间点 */
  437. const recordStartTimePoint = async (res?: IPostMessage) => {
  438. console.error("开始录音");
  439. // 没有开始评测,不处理
  440. if (!evaluatingData.startBegin) return;
  441. let inteveral = res?.content?.inteveral || 0;
  442. if (browserInfo.ios) {
  443. inteveral *= 1000;
  444. }
  445. evaluatingData.backtime = inteveral || Date.now();
  446. console.log("🚀 ~ 开始时间点:", evaluatingData.backtime, "已经录的时间:", Date.now() - inteveral, "记录时间点:", Date.now());
  447. // 是否禁播
  448. if (evaluatingData.isDisabledPlayMusic) {
  449. return;
  450. }
  451. // 开始播放
  452. playMusic();
  453. };
  454. /**
  455. * 结束评测
  456. * @param isComplete 是否完整评测
  457. * @returns
  458. */
  459. export const handleEndEvaluat = (isComplete = false) => {
  460. // 没有开始评测 , 不是评测模式 , 不评分
  461. if (!evaluatingData.startBegin || state.modeType !== "evaluating") return;
  462. // 结束录音
  463. // api_stopRecording();
  464. // 结束评测
  465. console.log("评测结束1");
  466. endEvaluating({
  467. musicScoreId: state.examSongId,
  468. });
  469. // 评测作业如果不是完整评测,给出提示
  470. if (!isComplete && data.trainingType === "EVALUATION") {
  471. showToast({
  472. message: "完整演奏结束才算作业分数!",
  473. });
  474. } else {
  475. showLoadingToast({
  476. message: "评分中",
  477. duration: 0,
  478. overlay: true,
  479. overlayClass: styles.scoreMode,
  480. });
  481. }
  482. setTimeout(() => {
  483. evaluatingData.startBegin = false;
  484. }, 500);
  485. evaluatingData.isComplete = isComplete;
  486. // 如果开启了摄像头, 结束录制视频
  487. if (state.setting.camera) {
  488. console.log("结束录制视频");
  489. api_endCapture();
  490. }
  491. };
  492. /**
  493. * 结束评测(手动结束评测)
  494. */
  495. export const handleEndBegin = () => {
  496. handleEndEvaluat();
  497. handleStopPlay();
  498. };
  499. /**
  500. * 取消评测
  501. */
  502. export const handleCancelEvaluat = (cancelType?: string) => {
  503. evaluatingData.evaluatings = {};
  504. evaluatingData.startBegin = false;
  505. // 关闭提示
  506. closeToast();
  507. // 取消记录
  508. api_proxyServiceMessage({
  509. header: {
  510. commond: "recordCancel",
  511. type: "SOUND_COMPARE",
  512. status: 200,
  513. },
  514. });
  515. /**
  516. * 异常状态是取消评测(cancelEvaluating),正常结束时结束评测(endEvaluating)
  517. */
  518. // if (cancelType === "cancel") {
  519. // // 取消评测
  520. // cancelEvaluating();
  521. // } else {
  522. // endEvaluating({
  523. // musicScoreId: state.examSongId,
  524. // });
  525. // }
  526. cancelEvaluating();
  527. // 停止播放
  528. handleStopPlay();
  529. console.log("评测结束2");
  530. endEvaluating({
  531. musicScoreId: state.examSongId,
  532. });
  533. // 如果开启了摄像头, 结束录制视频
  534. if (state.setting.camera) {
  535. console.log("结束录制视频");
  536. api_endCapture();
  537. }
  538. };
  539. /** 查看报告 */
  540. export const handleViewReport = (key: "recordId" | "recordIdStr", type: "gym" | "colexiu" | "orchestra" | "instrument") => {
  541. const id = evaluatingData.resultData?.[key] || "";
  542. let url = "";
  543. switch (type) {
  544. case "gym":
  545. url = location.origin + location.pathname + "#/report/" + id;
  546. break;
  547. case "orchestra":
  548. url = location.origin + location.pathname + "report-share.html?id=" + id;
  549. break;
  550. case "instrument":
  551. url = location.origin + location.pathname + "#/evaluat-report?id=" + id + "&musicRenderType=" + state.musicRenderType;
  552. break;
  553. default:
  554. url = location.origin + location.pathname + "report-share.html?id=" + id;
  555. break;
  556. }
  557. api_openWebView({
  558. url,
  559. orientation: 0,
  560. isHideTitle: true, // 此处兼容安卓,意思为隐藏全部头部
  561. statusBarTextColor: false,
  562. isOpenLight: true,
  563. c_orientation: 0,
  564. });
  565. };
  566. // 隐藏存演奏按钮
  567. const handleComplexButton = (res?: IPostMessage) => {
  568. console.log("监听是否隐藏保存按钮", res);
  569. if (res?.content) {
  570. const { header, body } = res.content;
  571. state.isHideEvaluatReportSaveBtn = true;
  572. }
  573. };
  574. // 检测到APP发送的异常信息
  575. const handleAccompanyError = (res?: IPostMessage) => {
  576. console.log("异常信息返回", res);
  577. if (res?.content) {
  578. const { type, reson } = res.content;
  579. switch (type) {
  580. case "enterBackground":
  581. // App退到后台
  582. case "playError":
  583. // 播放异常
  584. case "socketError":
  585. // socket连接断开,评测中,则取消评测
  586. // 延迟检测中
  587. if (evaluatingData.soundEffectMode) {
  588. evaluatingData.socketErrorStatus = 0;
  589. evaluatingData.delayCheckSocketError = true;
  590. evaluatingData.socketErrorPop = type === "socketError" ? true : false;
  591. evaluatingData.accompanyErrorType = type;
  592. // api_checkSocketStatus()
  593. return;
  594. }
  595. // 评测中
  596. if (state.modeType === "evaluating" && evaluatingData.startBegin) {
  597. handleCancelEvaluat("cancel");
  598. }
  599. // 关闭节拍器
  600. closeTick();
  601. // socketerrror,才发送关闭延迟检测的消息
  602. if (type === "socketError") {
  603. api_closeDelayCheck({});
  604. }
  605. evaluatingData.socketErrorStatus = 0;
  606. evaluatingData.socketErrorPop = type === "socketError" ? true : false;
  607. evaluatingData.isErrorState = true;
  608. evaluatingData.accompanyErrorType = type;
  609. resetPlaybackToStart();
  610. break;
  611. case "recordError":
  612. // 录音异常
  613. break;
  614. default:
  615. break;
  616. }
  617. }
  618. };
  619. // 监测socket状态,是否已经成功连接
  620. const handleSocketStatus = (res?: IPostMessage) => {
  621. if (res?.content?.status === "connected") {
  622. const currentTime = +new Date();
  623. evaluatingData.delayCheckSocketError = false;
  624. const diffTime = currentTime - socketStartTime;
  625. if (diffTime < 1000) {
  626. const remainingTime = 1000 - diffTime;
  627. setTimeout(() => {
  628. evaluatingData.socketErrorStatus = 2;
  629. }, remainingTime);
  630. }
  631. }
  632. };
  633. // 评测出现异常,再试一次
  634. export const hanldeConfirmPop = async () => {
  635. api_checkSocketStatus();
  636. evaluatingData.socketErrorStatus = 1;
  637. socketStartTime = +new Date();
  638. };
  639. // 关闭异常弹窗
  640. export const hanldeClosePop = () => {
  641. evaluatingData.socketErrorPop = false;
  642. evaluatingData.socketErrorStatus = 0;
  643. };
  644. export default defineComponent({
  645. name: "evaluating",
  646. setup() {
  647. const pageVisibility = usePageVisibility();
  648. // 需要记录的数据
  649. const record_old_data = reactive({
  650. /** 指法 */
  651. finger: false,
  652. /** 原音伴奏 */
  653. play_mode: "" as IPlayState,
  654. /** 评测是否要伴奏 */
  655. enableAccompaniment: true,
  656. });
  657. /** 记录状态 */
  658. const hanlde_record = () => {
  659. // 取消指法
  660. record_old_data.finger = state.setting.displayFingering;
  661. state.setting.displayFingering = false;
  662. // 切换为伴奏
  663. record_old_data.play_mode = state.playSource;
  664. record_old_data.enableAccompaniment = state.setting.enableAccompaniment;
  665. // 如果关闭伴奏,评测静音
  666. if (!record_old_data.enableAccompaniment) {
  667. console.log("关闭伴奏");
  668. toggleMutePlayAudio(record_old_data.play_mode === "music" ? "music" : record_old_data.play_mode === "background" ? "background" : "mingSong", true);
  669. }
  670. };
  671. /** 还原状态 */
  672. const handle_reduction = () => {
  673. // 还原指法
  674. state.setting.displayFingering = record_old_data.finger;
  675. state.playSource = record_old_data.play_mode;
  676. // 如果关闭伴奏, 结束评测取消静音
  677. if (!record_old_data.enableAccompaniment) {
  678. toggleMutePlayAudio(record_old_data.play_mode === "music" ? "music" : record_old_data.play_mode === "background" ? "background" : "mingSong", false);
  679. }
  680. };
  681. watch(pageVisibility, (value) => {
  682. if (value == "hidden" && evaluatingData.startBegin) {
  683. // handleEndBegin();
  684. }
  685. });
  686. watch(
  687. () => evaluatingData.socketErrorStatus,
  688. () => {
  689. if (evaluatingData.socketErrorStatus === 2) {
  690. setTimeout(() => {
  691. evaluatingData.socketErrorPop = false;
  692. // evaluatingData.socketErrorStatus = 0
  693. }, 1000);
  694. }
  695. }
  696. );
  697. watch(
  698. () => evaluatingData.socketErrorPop,
  699. () => {
  700. if (evaluatingData.socketErrorPop && state.setting.soundEffect) {
  701. // 监听到socket状态异常,需要关闭延迟检测
  702. api_closeDelayCheck({});
  703. }
  704. }
  705. );
  706. onMounted(() => {
  707. resetPlaybackToStart();
  708. hanlde_record();
  709. evaluatingData.resultData = {};
  710. // evaluatingData.resulstMode = true;
  711. // evaluatingData.resultData = {...getLeveByScore(10), score: 10, intonation: 10, cadence: 30, integrity: 40}
  712. // console.log("🚀 ~ evaluatingData.resultData:", evaluatingData.resultData)
  713. evaluatingData.evaluatings = {};
  714. evaluatingData.soundEffectFrequency = 0;
  715. evaluatingData.checkStep = 0;
  716. evaluatingData.rendered = true;
  717. sendResult(handleScoreResult);
  718. hideComplexButton(handleComplexButton, true);
  719. api_recordStartTime(recordStartTimePoint);
  720. addAccompanyError(handleAccompanyError);
  721. addSocketStatus(handleSocketStatus);
  722. // 不是选段模式评测, 就清空已选段
  723. if (!state.isSelectMeasureMode) {
  724. clearSelection();
  725. }
  726. console.log("加载评测模块成功");
  727. });
  728. onUnmounted(() => {
  729. evaluatingData.checkEnd = false;
  730. evaluatingData.rendered = false;
  731. resetPlaybackToStart();
  732. removeResult(handleScoreResult);
  733. hideComplexButton(() => {}, false);
  734. api_remove_recordStartTime(recordStartTimePoint);
  735. handle_reduction();
  736. removeAccompanyError(handleAccompanyError);
  737. if (evaluatingData.socketErrorPop && state.setting.soundEffect) {
  738. console.log('延迟检测出错')
  739. } else {
  740. removeSocketStatus(handleSocketStatus);
  741. }
  742. api_disconnectSocket();
  743. console.log("卸载评测模块成功");
  744. });
  745. return () => (
  746. <div>
  747. {/** 预加载一下断网需要用到的图片 */}
  748. <div class={styles.hiddenPop}>
  749. <img src={popImgs.icon_bg} />
  750. <img src={popImgs.icon_btn} />
  751. <img src={popImgs.icon_success} />
  752. <img src={popImgs.icon_close} />
  753. </div>
  754. <Popup teleport="body" closeOnClickOverlay={false} class={["popup-custom", "van-scale"]} transition="van-scale" v-model:show={evaluatingData.socketErrorPop}>
  755. <AbnormalPop onConfirm={hanldeConfirmPop} onClose={hanldeClosePop} />
  756. </Popup>
  757. </div>
  758. );
  759. },
  760. });