index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import styles from "./index.module.less";
  2. import { Snackbar } from "@varlet/ui";
  3. import { closeToast, showLoadingToast, showToast } 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_stopRecording,
  19. api_recordStartTime,
  20. api_remove_recordStartTime,
  21. api_startCapture,
  22. api_endCapture,
  23. api_getDeviceDelay,
  24. hideComplexButton,
  25. } from "/src/helpers/communication";
  26. import state, {
  27. IPlayState,
  28. clearSelection,
  29. handleStopPlay,
  30. onPlay,
  31. resetPlaybackToStart,
  32. togglePlay,
  33. } from "/src/state";
  34. import { IPostMessage } from "/src/utils/native-message";
  35. import { usePageVisibility } from "@vant/use";
  36. import { browser } from "/src/utils";
  37. import { getAudioCurrentTime, toggleMutePlayAudio } from "../audio-list";
  38. import { handleStartTick } from "../tick";
  39. const browserInfo = browser();
  40. export const evaluatingData = reactive({
  41. /** 评测数据 */
  42. contentData: {} as any,
  43. /** 评测模块是否加载完成 */
  44. rendered: false,
  45. earphone: false, // 是否插入耳机
  46. soundEffect: false, // 是否效音
  47. soundEffectFrequency: 0, // 效音频率
  48. checkStep: 0, // 执行步骤
  49. checkEnd: false, // 检测结束
  50. earphoneMode: false, // 耳机弹窗
  51. soundEffectMode: false, // 效音弹窗
  52. websocketState: false, // websocket连接状态
  53. /**是否开始播放 */
  54. startBegin: false, // 开始
  55. backtime: 0, // 延迟时间
  56. /** 已经评测的数据 */
  57. evaluatings: {} as IEvaluatings,
  58. /** 评测结果 */
  59. resultData: {} as any,
  60. /** 评测结果弹窗 */
  61. resulstMode: false,
  62. /** 是否是完整评测 */
  63. isComplete: false,
  64. /** */
  65. isDisabledPlayMusic: false,
  66. });
  67. /** 点击开始评测按钮 */
  68. export const handleStartEvaluat = () => {
  69. if (state.modeType === "evaluating") {
  70. handleCancelEvaluat();
  71. } else {
  72. handleStopPlay();
  73. }
  74. state.modeType = state.modeType === "evaluating" ? "practise" : "evaluating";
  75. if (state.modeType !== "evaluating") {
  76. // 切换到练习模式,卸载评测模块
  77. evaluatingData.rendered = false;
  78. }
  79. };
  80. const check_currentTime = () => {
  81. let preTime = 0;
  82. // 选段评测模式
  83. if (state.isSelectMeasureMode) {
  84. preTime = state.section[0].time * 1000;
  85. }
  86. const currentTime = getAudioCurrentTime() * 1000 - preTime;
  87. // console.log('播放进度music', currentTime, 'preTime:' + preTime)
  88. if (currentTime >= 500) {
  89. sendEvaluatingOffsetTime(500);
  90. return;
  91. }
  92. setTimeout(() => {
  93. check_currentTime();
  94. }, 10);
  95. };
  96. /** 开始播放发送延迟时间 */
  97. export const sendEvaluatingOffsetTime = async (currentTime: number) => {
  98. // 没有开始时间点, 不处理
  99. if (!evaluatingData.backtime) return;
  100. const nowTime = Date.now();
  101. const delayTime = nowTime - evaluatingData.backtime - currentTime;
  102. console.error("真正播放延迟", delayTime, "currentTime:", currentTime);
  103. await api_proxyServiceMessage({
  104. header: {
  105. commond: "audioPlayStart",
  106. type: "SOUND_COMPARE",
  107. },
  108. body: {
  109. offsetTime: delayTime < 0 ? 0 : delayTime,
  110. micDelay: 0,
  111. },
  112. });
  113. };
  114. /** 检测耳机 */
  115. const checkUseEarphone = async () => {
  116. const res = await getEarphone();
  117. return res?.content?.checkIsWired || false;
  118. };
  119. /**
  120. * 开始录音
  121. */
  122. const handleStartSoundCheck = () => {
  123. startSoundCheck();
  124. };
  125. /** 结束录音 */
  126. export const handleEndSoundCheck = () => {
  127. endSoundCheck();
  128. };
  129. /** 连接websocket */
  130. export const connectWebsocket = async (content: any) => {
  131. evaluatingData.contentData = content;
  132. evaluatingData.websocketState = true;
  133. };
  134. /**
  135. * 执行检测
  136. */
  137. export const handlePerformDetection = async () => {
  138. // 检测完成不检测了
  139. if (evaluatingData.checkEnd) return;
  140. // 延迟检测
  141. if (evaluatingData.checkStep === 0) {
  142. evaluatingData.checkStep = 5;
  143. // 没有设备延迟数据 或 开启了效音 显示检测组件,并持续检测耳机状态
  144. if (state.setting.soundEffect) {
  145. evaluatingData.soundEffectMode = true;
  146. return;
  147. }
  148. const delayTime = await api_getDeviceDelay();
  149. console.log("🚀 ~ delayTime:", delayTime);
  150. if (!delayTime) {
  151. evaluatingData.soundEffectMode = true;
  152. return;
  153. }
  154. handlePerformDetection();
  155. return;
  156. }
  157. // 检测耳机
  158. if ((evaluatingData.checkStep = 5)) {
  159. evaluatingData.checkStep = 10;
  160. const erji = await checkUseEarphone();
  161. if (!erji) {
  162. evaluatingData.earphoneMode = true;
  163. return;
  164. }
  165. handlePerformDetection();
  166. return;
  167. }
  168. // 效音
  169. // if (evaluatingData.checkStep === 7) {
  170. // // 是否需要开启效音
  171. // evaluatingData.checkStep = 10;
  172. // if (state.setting.soundEffect && !state.isPercussion) {
  173. // evaluatingData.soundEffectMode = true;
  174. // handleStartSoundCheck();
  175. // return
  176. // }
  177. // handlePerformDetection();
  178. // return;
  179. // }
  180. // 效验完成
  181. if (evaluatingData.checkStep === 10) {
  182. evaluatingData.checkEnd = true;
  183. }
  184. };
  185. /** 记录小节分数 */
  186. export const addMeasureScore = (measureScore: any, show = true) => {
  187. evaluatingData.evaluatings[measureScore.measureRenderIndex] = {
  188. ...measureScore,
  189. leve: getLeveByScoreMeasure(measureScore.score),
  190. show,
  191. };
  192. // console.log("🚀 ~ measureScore:", evaluatingData.evaluatings[measureScore.measureRenderIndex])
  193. };
  194. const handleScoreResult = (res?: IPostMessage) => {
  195. if (res?.content) {
  196. const { header, body } = res.content;
  197. // 效音返回
  198. if (header.commond === "checking") {
  199. evaluatingData.soundEffectFrequency = body.frequency;
  200. }
  201. const productNum = () => {
  202. return Math.floor(Math.random() * 20) + (80);
  203. }
  204. // 小节评分返回
  205. if (header?.commond === "measureScore") {
  206. console.log("🚀 ~ 评测返回:", res);
  207. // 录视频
  208. body.score = productNum();
  209. addMeasureScore(body);
  210. }
  211. // 评测结束返回
  212. if (header?.commond === "overall") {
  213. console.log("🚀 ~ 评测返回:", res);
  214. // console.log("评测结束", body);
  215. // 录视频
  216. body.score = productNum();
  217. body.intonation = productNum();
  218. body.cadence = productNum();
  219. body.integrity = productNum();
  220. evaluatingData.resulstMode = true;
  221. evaluatingData.resultData = {
  222. ...body,
  223. ...getLeveByScore(body.score),
  224. };
  225. // console.log("🚀 ~ evaluatingData.resultData:", evaluatingData.resultData)
  226. closeToast();
  227. }
  228. }
  229. };
  230. /** 开始评测 */
  231. export const handleStartBegin = async () => {
  232. evaluatingData.isComplete = false;
  233. evaluatingData.evaluatings = {};
  234. evaluatingData.resultData = {};
  235. evaluatingData.backtime = 0;
  236. resetPlaybackToStart();
  237. const res = await startEvaluating(evaluatingData.contentData);
  238. if (res?.api !== "startEvaluating") {
  239. Snackbar.error("请在APP端进行评测");
  240. evaluatingData.startBegin = false;
  241. return;
  242. }
  243. if (res?.content?.reson) {
  244. showToast(res.content.reson);
  245. evaluatingData.startBegin = false;
  246. return;
  247. }
  248. evaluatingData.startBegin = true;
  249. if (evaluatingData.isDisabledPlayMusic) {
  250. state.playState = state.playState === "paused" ? "play" : "paused";
  251. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  252. if (state.playState === "play" && state.needTick) {
  253. const tickend = await handleStartTick();
  254. // console.log("🚀 ~ tickend:", tickend)
  255. // 节拍器返回false, 取消播放
  256. if (!tickend) {
  257. state.playState = "paused";
  258. evaluatingData.startBegin = false;
  259. return;
  260. }
  261. }
  262. onPlay();
  263. }
  264. //开始录音
  265. await api_startRecording();
  266. // 如果开启了摄像头, 开启录制视频
  267. if (state.setting.camera && state.setting.saveToAlbum) {
  268. console.log("开始录制视频");
  269. api_startCapture();
  270. }
  271. };
  272. /** 播放音乐 */
  273. const playMusic = async () => {
  274. const playState = await togglePlay("play");
  275. // 取消播放,停止播放
  276. if (!playState) {
  277. evaluatingData.startBegin = false;
  278. handleCancelEvaluat();
  279. return;
  280. }
  281. // 检测播放进度, 计算延迟
  282. check_currentTime();
  283. // 如果开启了摄像头, 开启录制视频
  284. if (state.setting.camera && state.setting.saveToAlbum) {
  285. console.log("开始录制视频");
  286. api_startCapture();
  287. }
  288. };
  289. let _audio: HTMLAudioElement;
  290. /** 录音开始,记录开始时间点 */
  291. const recordStartTimePoint = async (res?: IPostMessage) => {
  292. console.error("开始录音");
  293. // 没有开始评测,不处理
  294. if (!evaluatingData.startBegin) return;
  295. let inteveral = res?.content?.inteveral || 0;
  296. if (browserInfo.ios) {
  297. inteveral *= 1000;
  298. }
  299. evaluatingData.backtime = inteveral || Date.now();
  300. console.log(
  301. "🚀 ~ 开始时间点:",
  302. evaluatingData.backtime,
  303. "已经录的时间:",
  304. Date.now() - inteveral,
  305. "记录时间点:",
  306. Date.now()
  307. );
  308. // 是否禁播
  309. if (evaluatingData.isDisabledPlayMusic) {
  310. return;
  311. }
  312. // 开始播放
  313. playMusic();
  314. };
  315. /**
  316. * 结束评测
  317. * @param isComplete 是否完整评测
  318. * @returns
  319. */
  320. export const handleEndEvaluat = (isComplete = false) => {
  321. // 没有开始评测 , 不是评测模式 , 不评分
  322. if (!evaluatingData.startBegin || state.modeType !== "evaluating") return;
  323. evaluatingData.startBegin = false;
  324. // 结束录音
  325. api_stopRecording();
  326. // 结束评测
  327. endEvaluating({
  328. musicScoreId: state.examSongId,
  329. });
  330. showLoadingToast({
  331. message: "评分中",
  332. duration: 0,
  333. overlay: true,
  334. overlayClass: styles.scoreMode,
  335. });
  336. evaluatingData.isComplete = isComplete;
  337. // 如果开启了摄像头, 结束录制视频
  338. if (state.setting.camera && state.setting.saveToAlbum) {
  339. console.log("结束录制视频");
  340. api_endCapture();
  341. }
  342. };
  343. /**
  344. * 结束评测
  345. */
  346. export const handleEndBegin = () => {
  347. handleEndEvaluat();
  348. handleStopPlay();
  349. };
  350. /**
  351. * 取消评测
  352. */
  353. export const handleCancelEvaluat = () => {
  354. evaluatingData.evaluatings = {};
  355. evaluatingData.startBegin = false;
  356. // 关闭提示
  357. closeToast();
  358. // 取消记录
  359. api_proxyServiceMessage({
  360. header: {
  361. commond: "recordCancel",
  362. type: "SOUND_COMPARE",
  363. status: 200,
  364. },
  365. });
  366. // 取消评测
  367. cancelEvaluating();
  368. // 停止播放
  369. handleStopPlay();
  370. };
  371. /** 查看报告 */
  372. export const handleViewReport = (
  373. key: "recordId" | "recordIdStr",
  374. type: "gym" | "colexiu" | "orchestra" | "instrument"
  375. ) => {
  376. const id = evaluatingData.resultData?.[key] || "";
  377. let url = "";
  378. switch (type) {
  379. case "gym":
  380. url = location.origin + location.pathname + "#/report/" + id;
  381. break;
  382. case "orchestra":
  383. url = location.origin + location.pathname + "report-share.html?id=" + id;
  384. break;
  385. case "instrument":
  386. url = location.origin + location.pathname + "#/evaluat-report?id=" + id;
  387. break;
  388. default:
  389. url = location.origin + location.pathname + "report-share.html?id=" + id;
  390. break;
  391. }
  392. api_openWebView({
  393. url,
  394. orientation: 0,
  395. isHideTitle: true, // 此处兼容安卓,意思为隐藏全部头部
  396. statusBarTextColor: false,
  397. isOpenLight: true,
  398. c_orientation: 0,
  399. });
  400. };
  401. // 隐藏存演奏按钮
  402. const handleComplexButton = (res?: IPostMessage) => {
  403. console.log('监听是否隐藏保存按钮', res)
  404. if (res?.content) {
  405. const { header, body } = res.content;
  406. state.isHideEvaluatReportSaveBtn = true
  407. }
  408. };
  409. export default defineComponent({
  410. name: "evaluating",
  411. setup() {
  412. const pageVisibility = usePageVisibility();
  413. // 需要记录的数据
  414. const record_old_data = reactive({
  415. /** 指法 */
  416. finger: false,
  417. /** 原音伴奏 */
  418. play_mode: "" as IPlayState,
  419. /** 评测是否要伴奏 */
  420. enableAccompaniment: true,
  421. });
  422. /** 记录状态 */
  423. const hanlde_record = () => {
  424. // 取消指法
  425. record_old_data.finger = state.setting.displayFingering;
  426. state.setting.displayFingering = false;
  427. // 切换为伴奏
  428. record_old_data.play_mode = state.playSource;
  429. record_old_data.enableAccompaniment = state.setting.enableAccompaniment;
  430. // 如果关闭伴奏,评测静音
  431. if (!record_old_data.enableAccompaniment) {
  432. console.log("关闭伴奏");
  433. toggleMutePlayAudio(record_old_data.play_mode === "music" ? "music" : "background", true);
  434. }
  435. };
  436. /** 还原状态 */
  437. const handle_reduction = () => {
  438. // 还原指法
  439. state.setting.displayFingering = record_old_data.finger;
  440. state.playSource = record_old_data.play_mode;
  441. // 如果关闭伴奏, 结束评测取消静音
  442. if (!record_old_data.enableAccompaniment) {
  443. toggleMutePlayAudio(record_old_data.play_mode === "music" ? "music" : "background", false);
  444. }
  445. };
  446. watch(pageVisibility, (value) => {
  447. if (value == "hidden" && evaluatingData.startBegin) {
  448. handleEndBegin();
  449. }
  450. });
  451. onMounted(() => {
  452. resetPlaybackToStart();
  453. hanlde_record();
  454. evaluatingData.resultData = {};
  455. // evaluatingData.resulstMode = true;
  456. // evaluatingData.resultData = {...getLeveByScore(10), score: 10, intonation: 10, cadence: 30, integrity: 40}
  457. // console.log("🚀 ~ evaluatingData.resultData:", evaluatingData.resultData)
  458. evaluatingData.evaluatings = {};
  459. evaluatingData.soundEffectFrequency = 0;
  460. evaluatingData.checkStep = 0;
  461. evaluatingData.rendered = true;
  462. sendResult(handleScoreResult);
  463. hideComplexButton(handleComplexButton, true);
  464. api_recordStartTime(recordStartTimePoint);
  465. // 不是选段模式评测, 就清空已选段
  466. if (!state.isSelectMeasureMode) {
  467. clearSelection();
  468. }
  469. console.log("加载评测模块成功");
  470. });
  471. onUnmounted(() => {
  472. evaluatingData.checkEnd = false;
  473. evaluatingData.rendered = false;
  474. resetPlaybackToStart();
  475. removeResult(handleScoreResult);
  476. hideComplexButton(() => {}, false);
  477. api_remove_recordStartTime(recordStartTimePoint);
  478. handle_reduction();
  479. console.log("卸载评测模块成功");
  480. });
  481. return () => <div></div>;
  482. },
  483. });