index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. // #8720 bug修复
  188. for(let idx in evaluatingData.evaluatings) {
  189. evaluatingData.evaluatings[idx].show = false
  190. }
  191. evaluatingData.evaluatings[measureScore.measureRenderIndex] = {
  192. ...measureScore,
  193. leve: getLeveByScoreMeasure(measureScore.score),
  194. show,
  195. };
  196. // console.log("🚀 ~ measureScore:", evaluatingData.evaluatings)
  197. };
  198. const handleScoreResult = (res?: IPostMessage) => {
  199. console.log('返回', res)
  200. if (res?.content) {
  201. const { header, body } = res.content;
  202. // 效音返回
  203. if (header.commond === "checking") {
  204. evaluatingData.soundEffectFrequency = body.frequency;
  205. }
  206. // 小节评分返回
  207. if (header?.commond === "measureScore") {
  208. console.log("🚀 ~ 评测返回:", res);
  209. addMeasureScore(body);
  210. }
  211. // 评测结束返回
  212. if (header?.commond === "overall") {
  213. console.log("🚀 ~ 评测返回:", res);
  214. // console.log("评测结束", body);
  215. state.isHideEvaluatReportSaveBtn = false;
  216. evaluatingData.resulstMode = true;
  217. evaluatingData.resultData = {
  218. ...body,
  219. ...getLeveByScore(body.score),
  220. };
  221. // console.log("🚀 ~ evaluatingData.resultData:", evaluatingData.resultData)
  222. closeToast();
  223. }
  224. }
  225. };
  226. /** 开始评测 */
  227. export const handleStartBegin = async () => {
  228. evaluatingData.isComplete = false;
  229. evaluatingData.evaluatings = {};
  230. evaluatingData.resultData = {};
  231. evaluatingData.backtime = 0;
  232. resetPlaybackToStart();
  233. const res = await startEvaluating(evaluatingData.contentData);
  234. if (res?.api !== "startEvaluating") {
  235. Snackbar.error("请在APP端进行评测");
  236. evaluatingData.startBegin = false;
  237. return;
  238. }
  239. if (res?.content?.reson) {
  240. showToast(res.content.reson);
  241. evaluatingData.startBegin = false;
  242. return;
  243. }
  244. evaluatingData.startBegin = true;
  245. if (evaluatingData.isDisabledPlayMusic) {
  246. state.playState = state.playState === "paused" ? "play" : "paused";
  247. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  248. if (state.playState === "play" && state.needTick) {
  249. const tickend = await handleStartTick();
  250. // console.log("🚀 ~ tickend:", tickend)
  251. // 节拍器返回false, 取消播放
  252. if (!tickend) {
  253. state.playState = "paused";
  254. evaluatingData.startBegin = false;
  255. return;
  256. }
  257. }
  258. onPlay();
  259. }
  260. //开始录音
  261. await api_startRecording();
  262. // 如果开启了摄像头, 开启录制视频
  263. if (state.setting.camera) {
  264. console.log("开始录制视频");
  265. api_startCapture();
  266. }
  267. };
  268. /** 播放音乐 */
  269. const playMusic = async () => {
  270. const playState = await togglePlay("play");
  271. // 取消播放,停止播放
  272. if (!playState) {
  273. evaluatingData.startBegin = false;
  274. handleCancelEvaluat();
  275. return;
  276. }
  277. // 检测播放进度, 计算延迟
  278. check_currentTime();
  279. // 如果开启了摄像头, 开启录制视频
  280. if (state.setting.camera) {
  281. console.log("开始录制视频");
  282. api_startCapture();
  283. }
  284. };
  285. let _audio: HTMLAudioElement;
  286. /** 录音开始,记录开始时间点 */
  287. const recordStartTimePoint = async (res?: IPostMessage) => {
  288. console.error("开始录音");
  289. // 没有开始评测,不处理
  290. if (!evaluatingData.startBegin) return;
  291. let inteveral = res?.content?.inteveral || 0;
  292. if (browserInfo.ios) {
  293. inteveral *= 1000;
  294. }
  295. evaluatingData.backtime = inteveral || Date.now();
  296. console.log(
  297. "🚀 ~ 开始时间点:",
  298. evaluatingData.backtime,
  299. "已经录的时间:",
  300. Date.now() - inteveral,
  301. "记录时间点:",
  302. Date.now()
  303. );
  304. // 是否禁播
  305. if (evaluatingData.isDisabledPlayMusic) {
  306. return;
  307. }
  308. // 开始播放
  309. playMusic();
  310. };
  311. /**
  312. * 结束评测
  313. * @param isComplete 是否完整评测
  314. * @returns
  315. */
  316. export const handleEndEvaluat = (isComplete = false) => {
  317. // 没有开始评测 , 不是评测模式 , 不评分
  318. if (!evaluatingData.startBegin || state.modeType !== "evaluating") return;
  319. evaluatingData.startBegin = false;
  320. // 结束录音
  321. api_stopRecording();
  322. // 结束评测
  323. endEvaluating({
  324. musicScoreId: state.examSongId,
  325. });
  326. showLoadingToast({
  327. message: "评分中",
  328. duration: 0,
  329. overlay: true,
  330. overlayClass: styles.scoreMode,
  331. });
  332. evaluatingData.isComplete = isComplete;
  333. // 如果开启了摄像头, 结束录制视频
  334. if (state.setting.camera) {
  335. console.log("结束录制视频");
  336. api_endCapture();
  337. }
  338. };
  339. /**
  340. * 结束评测
  341. */
  342. export const handleEndBegin = () => {
  343. handleEndEvaluat();
  344. handleStopPlay();
  345. };
  346. /**
  347. * 取消评测
  348. */
  349. export const handleCancelEvaluat = () => {
  350. evaluatingData.evaluatings = {};
  351. evaluatingData.startBegin = false;
  352. // 关闭提示
  353. closeToast();
  354. // 取消记录
  355. api_proxyServiceMessage({
  356. header: {
  357. commond: "recordCancel",
  358. type: "SOUND_COMPARE",
  359. status: 200,
  360. },
  361. });
  362. // 取消评测
  363. cancelEvaluating();
  364. // 停止播放
  365. handleStopPlay();
  366. };
  367. /** 查看报告 */
  368. export const handleViewReport = (
  369. key: "recordId" | "recordIdStr",
  370. type: "gym" | "colexiu" | "orchestra" | "instrument"
  371. ) => {
  372. const id = evaluatingData.resultData?.[key] || "";
  373. let url = "";
  374. switch (type) {
  375. case "gym":
  376. url = location.origin + location.pathname + "#/report/" + id;
  377. break;
  378. case "orchestra":
  379. url = location.origin + location.pathname + "report-share.html?id=" + id;
  380. break;
  381. case "instrument":
  382. url = location.origin + location.pathname + "#/evaluat-report?id=" + id;
  383. break;
  384. default:
  385. url = location.origin + location.pathname + "report-share.html?id=" + id;
  386. break;
  387. }
  388. api_openWebView({
  389. url,
  390. orientation: 0,
  391. isHideTitle: true, // 此处兼容安卓,意思为隐藏全部头部
  392. statusBarTextColor: false,
  393. isOpenLight: true,
  394. c_orientation: 0,
  395. });
  396. };
  397. // 隐藏存演奏按钮
  398. const handleComplexButton = (res?: IPostMessage) => {
  399. console.log('监听是否隐藏保存按钮', res)
  400. if (res?.content) {
  401. const { header, body } = res.content;
  402. state.isHideEvaluatReportSaveBtn = true
  403. }
  404. };
  405. export default defineComponent({
  406. name: "evaluating",
  407. setup() {
  408. const pageVisibility = usePageVisibility();
  409. // 需要记录的数据
  410. const record_old_data = reactive({
  411. /** 指法 */
  412. finger: false,
  413. /** 原音伴奏 */
  414. play_mode: "" as IPlayState,
  415. /** 评测是否要伴奏 */
  416. enableAccompaniment: true,
  417. });
  418. /** 记录状态 */
  419. const hanlde_record = () => {
  420. // 取消指法
  421. record_old_data.finger = state.setting.displayFingering;
  422. state.setting.displayFingering = false;
  423. // 切换为伴奏
  424. record_old_data.play_mode = state.playSource;
  425. record_old_data.enableAccompaniment = state.setting.enableAccompaniment;
  426. // 如果关闭伴奏,评测静音
  427. if (!record_old_data.enableAccompaniment) {
  428. console.log("关闭伴奏");
  429. toggleMutePlayAudio(record_old_data.play_mode === "music" ? "music" : "background", true);
  430. }
  431. };
  432. /** 还原状态 */
  433. const handle_reduction = () => {
  434. // 还原指法
  435. state.setting.displayFingering = record_old_data.finger;
  436. state.playSource = record_old_data.play_mode;
  437. // 如果关闭伴奏, 结束评测取消静音
  438. if (!record_old_data.enableAccompaniment) {
  439. toggleMutePlayAudio(record_old_data.play_mode === "music" ? "music" : "background", false);
  440. }
  441. };
  442. watch(pageVisibility, (value) => {
  443. if (value == "hidden" && evaluatingData.startBegin) {
  444. handleEndBegin();
  445. }
  446. });
  447. onMounted(() => {
  448. resetPlaybackToStart();
  449. hanlde_record();
  450. evaluatingData.resultData = {};
  451. // evaluatingData.resulstMode = true;
  452. // evaluatingData.resultData = {...getLeveByScore(10), score: 10, intonation: 10, cadence: 30, integrity: 40}
  453. // console.log("🚀 ~ evaluatingData.resultData:", evaluatingData.resultData)
  454. evaluatingData.evaluatings = {};
  455. evaluatingData.soundEffectFrequency = 0;
  456. evaluatingData.checkStep = 0;
  457. evaluatingData.rendered = true;
  458. sendResult(handleScoreResult);
  459. hideComplexButton(handleComplexButton, true);
  460. api_recordStartTime(recordStartTimePoint);
  461. // 不是选段模式评测, 就清空已选段
  462. if (!state.isSelectMeasureMode) {
  463. clearSelection();
  464. }
  465. console.log("加载评测模块成功");
  466. });
  467. onUnmounted(() => {
  468. evaluatingData.checkEnd = false;
  469. evaluatingData.rendered = false;
  470. resetPlaybackToStart();
  471. removeResult(handleScoreResult);
  472. hideComplexButton(() => {}, false);
  473. api_remove_recordStartTime(recordStartTimePoint);
  474. handle_reduction();
  475. console.log("卸载评测模块成功");
  476. });
  477. return () => <div></div>;
  478. },
  479. });