evaluating.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. import { Button, Toast, Popup } from 'vant'
  2. import { defineComponent, onBeforeUnmount, onMounted, Ref, ref, Teleport, Transition, reactive } from 'vue'
  3. import '@dotlottie/player-component'
  4. import detailState, { isRhythmicExercises } from '/src/pages/detail/state'
  5. import SettingState from '/src/pages/detail/setting-state'
  6. import {
  7. IPostMessage,
  8. listenerMessage,
  9. postMessage,
  10. promisefiyPostMessage,
  11. removeListenerMessage,
  12. CallBack
  13. } from '/src/helpers/native-message'
  14. import { browser } from '/src/helpers/utils'
  15. import runtime, * as RuntimeUtils from '/src/pages/detail/runtime'
  16. import { getBoundingBoxByverticalNote, getNoteByMeasuresSlursStart, getParentNote } from '/src/pages/detail/helpers'
  17. import { handleCheckEvaluatStatus, useClientType, useOriginSearch } from '../uses'
  18. import { startButtonShow } from './index'
  19. import { getLeveByScoreMeasure } from '/src/pages/detail/evaluating/helper'
  20. import Evaluating, { evaluatingShow } from '../popups/evaluating'
  21. // @ts-ignore
  22. import styles from './index.module.less'
  23. import { Vue3Lottie } from 'vue3-lottie'
  24. import startData from './data/start_new.json'
  25. import startingData from './data/starting_new.json'
  26. import { unitTestData } from '../unitTest'
  27. import iconEvaluatingStart from './icons/icon-evaluatingStart.png'
  28. import qs from 'query-string'
  29. import CheckDelayPopup from "/src/pages/detail/CheckDelayPopup";
  30. import Headphone, { HeadphoneData } from "/src/pages/detail/Headphone";
  31. /** 初始化评测音频 */
  32. export const evaluatCreateMusicPlayer = () => {
  33. return new Promise((resolve) => {
  34. // 初始化曲谱音频 和效音音频
  35. postMessage(
  36. {
  37. api: "createMusicPlayer",
  38. content: {
  39. musicSrc: runtime.songs.background || runtime.songs.music, // 曲谱音频url
  40. tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  41. },
  42. },
  43. () => {
  44. if (browserInfo.ios) {
  45. resolve(true);
  46. }
  47. }
  48. );
  49. // 安卓不需要
  50. if(!browserInfo.ios){
  51. resolve(true)
  52. }
  53. })
  54. }
  55. const searchParams: any = qs.parse(location.search)
  56. /**
  57. * 节拍器时长
  58. * 评测模式时,应该传节拍器时长
  59. * 阶段评测时,判断是否从第一小节开始,并且曲子本身含有节拍器,需要传节拍器时长,否则传0
  60. */
  61. let actualBeatLength = 0
  62. let backtime = 0
  63. const initBehaviorId = '' + new Date().valueOf()
  64. const evaluating = ref(false)
  65. const playStatus: Ref<'connecting' | 'play' | 'stop'> = ref('stop')
  66. const endloading = ref(false)
  67. const connentLoading = ref(false)
  68. const playUrl: Ref<string> = ref('')
  69. const endResult = ref(null)
  70. const browserInfo = browser()
  71. const scoreList: any[] = []
  72. /** 延迟数据 */
  73. const delayData = reactive({
  74. /** 是否强制检测 */
  75. isForce: true,
  76. /** 弹窗 */
  77. open: false,
  78. /** 延迟次数 */
  79. count: 0,
  80. /** 延迟时间 */
  81. time: 0,
  82. /** 耳机状态 */
  83. erji: false,
  84. /** 检测状态 */
  85. checkStatus: 'init' as 'init' | 'ing' | 'error',
  86. step: 1,
  87. earPhoneType: "" as "" | "有线耳机" | "蓝牙耳机",
  88. })
  89. /** 获取耳机状态 */
  90. const getWiredStatus = (): Promise<boolean> => {
  91. return new Promise((resolve) => {
  92. const timer = setTimeout(() => {
  93. resolve(false);
  94. }, 1000)
  95. postMessage({
  96. api: "isWiredHeadsetOn",
  97. }, (res) => {
  98. delayData.earPhoneType = res?.content?.type || "";
  99. const checkIsWired = res?.content?.checkIsWired ? true : false;
  100. if (checkIsWired) {
  101. if (delayData.step <= 5) {
  102. delayData.step = 3
  103. }
  104. } else {
  105. if (delayData.step === 2 || delayData.step === 3) {
  106. delayData.step = 4
  107. }
  108. }
  109. clearTimeout(timer)
  110. resolve(checkIsWired);
  111. });
  112. });
  113. }
  114. const closeErji = () => {
  115. //
  116. }
  117. /** 获取设备延迟 */
  118. const getDeviceDelay = (): Promise<number> => {
  119. return new Promise((resolve) => {
  120. const timer = setTimeout(() => {
  121. resolve(0);
  122. }, 1000)
  123. postMessage({
  124. api: "getDeviceDelay",
  125. }, (res) => {
  126. const delay = res?.content?.value > 0 ? res?.content?.value : 0;
  127. clearTimeout(timer)
  128. resolve(delay);
  129. });
  130. });
  131. }
  132. /** 设备延迟检测结束 */
  133. const handleCheckDelayEnd = () => {
  134. if (delayData.erji) {
  135. closeErji();
  136. } else {
  137. // this.erjiShow = true;
  138. HeadphoneData.toggle();
  139. }
  140. }
  141. /** 评测效验 */
  142. const checkEvaluating = async () => {
  143. delayData.erji = await getWiredStatus();
  144. delayData.time = await getDeviceDelay();
  145. // 没有设备延迟数据,显示检测组件,并持续检测耳机状态
  146. if (!delayData.time || delayData.isForce) {
  147. delayData.open = (runtime.delayCheckFirst && searchParams.evaluatingRecord || !SettingState.sett.tuning) ? false : true
  148. delayData.count = 0;
  149. if (runtime.delayCheckFirst && searchParams.evaluatingRecord) {
  150. // closeErji()
  151. }
  152. return;
  153. }
  154. handleCheckDelayEnd()
  155. }
  156. /** 持续检测耳机状态 */
  157. const checkWiredStatus = () => {
  158. console.log('耳机状态',delayData.checkStatus)
  159. // 设备检测结束,停止获取耳机状态
  160. if (delayData.checkStatus !== 'ing' || delayData.open === false) {
  161. return
  162. }
  163. setTimeout(async () => {
  164. delayData.erji = await getWiredStatus();
  165. if (delayData.erji) {
  166. delayData.count = 0;
  167. delayData.time = 0;
  168. delayData.checkStatus = 'error'
  169. }
  170. checkWiredStatus();
  171. }, 1000)
  172. }
  173. /** 切换效音 */
  174. const handleToggleTune = (state: 'start' | 'stop' | 'finishTune') => {
  175. if (state === 'start') {
  176. delayData.step = 5
  177. // 开始效音
  178. postMessage({
  179. api: "startTune",
  180. content: {
  181. count: delayData.count + '',
  182. }
  183. }, (res) => {
  184. // 用户没有授权,需要重置状态
  185. if (res?.content?.reson) {
  186. delayData.step = 1
  187. delayData.checkStatus = 'init'
  188. } else {
  189. setTimeout(() => {
  190. handleToggleTune('stop')
  191. }, 1500)
  192. }
  193. })
  194. } else if (state === 'stop') {
  195. // 结束效音,触发时机: 1.监听后台效音返回 2.点击跳过效音或关闭效音
  196. postMessage({
  197. api: "endTune"
  198. })
  199. } else if (state === 'finishTune') {
  200. delayData.step = 6
  201. // 效音完成
  202. postMessage({
  203. api: "finishTune",
  204. }, (res) => {
  205. const result = res?.content?.result //1成功 0失败
  206. // Toast('检测延迟完成')
  207. // setTimeout(() => {
  208. // delayData.open = false
  209. // }, 500)
  210. })
  211. }
  212. }
  213. /** 开始效音 */
  214. const startTune = () => {
  215. // 带了耳机,停止播放效音
  216. if (delayData.erji) return;
  217. handleToggleTune('start')
  218. }
  219. /** 停止设备延迟检测 */
  220. const handleStopCheckDelay = () => {
  221. runtime.delayCheckFirst = true
  222. delayData.open = false
  223. delayData.checkStatus = 'init'
  224. delayData.step = 1
  225. handleToggleTune('stop')
  226. // this.close();
  227. }
  228. /** 开始检测设备延迟 */
  229. const handleStartCheckDelay = async () => {
  230. if (delayData.checkStatus === 'ing') return;
  231. delayData.step = 2
  232. delayData.erji = await getWiredStatus();
  233. if (delayData.erji) {
  234. delayData.checkStatus = 'error'
  235. return;
  236. }
  237. delayData.checkStatus = 'ing';
  238. setTimeout(() => {
  239. startTune()
  240. }, 2000)
  241. checkWiredStatus();
  242. }
  243. // frequency 频率, amplitude 振幅, decibels 分贝
  244. type TCriteria = "frequency" | "amplitude" | "decibels";
  245. /** 获取评测标准 */
  246. const getEvaluationCriteria = () => {
  247. let criteria: TCriteria = "frequency";
  248. // 声部打击乐
  249. if ([23, 113, 121].includes(detailState.subjectId)) {
  250. criteria = "amplitude";
  251. } else if (isRhythmicExercises()) {
  252. // 分类为节奏练习
  253. criteria = "decibels";
  254. }
  255. return criteria;
  256. };
  257. /**
  258. * 默认按照442计算的音符频率,此处转化为按照设置进行调整
  259. * @param num 频率
  260. * @returns 转化后频率
  261. */
  262. const formatPitch = (num?: number): number => {
  263. if (!num) {
  264. return -1
  265. }
  266. if (SettingState.sett.hertz && SettingState.sett.hertz !== 442) {
  267. return (num / 442) * SettingState.sett.hertz
  268. }
  269. return num
  270. }
  271. let starTime = 0
  272. const formatTimes = () => {
  273. const rate = runtime.speed / detailState.baseSpeed //1
  274. actualBeatLength = Math.round(detailState.times[0].fixtime * 1000 / rate)
  275. const difftime = detailState.times?.[0]?.difftime || 0
  276. let ListenMode = false
  277. let dontEvaluatingMode = false
  278. let skip = false
  279. const datas = []
  280. let times = detailState.times
  281. // 阶段评测前一个节拍的标示
  282. let preLyricsContent = ''
  283. let preTimes = []
  284. if (unitTestData.isSelectMeasureMode) {
  285. const startIndex = detailState.times.findIndex(
  286. (n: any) => n.NoteToGraphicalNoteObjectId == detailState.section[0].NoteToGraphicalNoteObjectId
  287. )
  288. const endIndex = detailState.times.findIndex(
  289. (n: any) => n.NoteToGraphicalNoteObjectId == detailState.section[1].NoteToGraphicalNoteObjectId
  290. )
  291. times = detailState.times.filter((n: any, index: number) => {
  292. return index >= startIndex && index <= endIndex
  293. })
  294. preTimes = detailState.times.filter((n: any, index: number) => {
  295. return index < startIndex
  296. })
  297. starTime = times[0].sourceRelativeTime || times[0].relativeTime
  298. actualBeatLength = startIndex == 0 && !detailState.needTick ? actualBeatLength : 0
  299. // console.log("🚀 ~ times", times, '开始小节', startIndex, actualBeatLength)
  300. }
  301. // 找到阶段评测,开始小节前面最近的是play或者listen的小节
  302. if (preTimes.length) {
  303. for (let index = preTimes.length-1; index >= 0; index--) {
  304. const item = preTimes[index]
  305. const note = getNoteByMeasuresSlursStart(item)
  306. if (note.formatLyricsEntries.contains('Play') || note.formatLyricsEntries.contains('Play...')) {
  307. preLyricsContent = 'Play'
  308. break
  309. }
  310. if (note.formatLyricsEntries.contains('Listen')) {
  311. preLyricsContent = 'Listen'
  312. break
  313. }
  314. }
  315. preLyricsContent = preLyricsContent ? preLyricsContent : 'Play'
  316. }
  317. let measureIndex = -1
  318. let recordMeasure = -1
  319. for (let index = 0; index < times.length; index++) {
  320. const item = times[index]
  321. const note = getNoteByMeasuresSlursStart(item)
  322. const rate = runtime.speed / detailState.baseSpeed //1
  323. const start = difftime + (item.sourceRelativeTime || item.relativeTime) - starTime
  324. const end = difftime + (item.sourceRelaEndtime || item.relaEndtime) - starTime
  325. // console.log(start, end, starTime)
  326. const isStaccato =
  327. typeof note.voiceEntry.isStaccato === 'function' ? note.voiceEntry.isStaccato() : note.voiceEntry.isStaccato
  328. const noteRate = isStaccato ? 0.5 : 1
  329. // console.log('注脚', note.formatLyricsEntries)
  330. // 如果阶段评测,开始小节没有注脚,则取前面最近的小节的注脚
  331. if (index == 0 && !note.formatLyricsEntries.length) {
  332. ListenMode = preLyricsContent === 'Play' ? false : preLyricsContent === 'Listen' ? true : false
  333. }
  334. if (note.formatLyricsEntries.contains('Play') || note.formatLyricsEntries.contains('Play...')) {
  335. ListenMode = false
  336. }
  337. if (note.formatLyricsEntries.contains('Listen')) {
  338. ListenMode = true
  339. }
  340. if (note.formatLyricsEntries.contains('纯律结束')) {
  341. dontEvaluatingMode = false
  342. }
  343. if (note.formatLyricsEntries.contains('纯律')) {
  344. dontEvaluatingMode = true
  345. }
  346. const nextNote = detailState.times[index + 1]
  347. if (skip && (note.stave || !note.noteElement.isRestFlag || (nextNote && !nextNote.noteElement.isRestFlag))) {
  348. skip = false
  349. }
  350. if (note.noteElement.isRestFlag && !!note.stave && !!nextNote && nextNote.noteElement.isRestFlag) {
  351. skip = true
  352. }
  353. if (note.measureOpenIndex != recordMeasure) {
  354. measureIndex++
  355. recordMeasure = note.measureOpenIndex
  356. }
  357. // console.log(note.measureOpenIndex , measureIndex, note.noteElement.sourceMeasure.measureListIndex)
  358. const data = {
  359. timeStamp: (start * 1000) / rate,
  360. duration: ((end * 1000) / rate - (start * 1000) / rate) * noteRate,
  361. frequency: formatPitch(item.noteElement?.pitch?.frequency),
  362. nextFrequency: formatPitch(item.noteElement?.pitch?.nextFrequency),
  363. prevFrequency: formatPitch(item.noteElement?.pitch?.prevFrequency),
  364. measureIndex: measureIndex, //note.measureOpenIndex,
  365. measureRenderIndex: note.noteElement.sourceMeasure.measureListIndex,
  366. dontEvaluating: ListenMode || dontEvaluatingMode || item.skipMode,
  367. musicalNotesIndex: index, //item.i,
  368. denominator: note.noteElement?.Length.denominator,
  369. isOrnament: !!note?.voiceEntry?.ornamentContainer,
  370. }
  371. // console.log('时间1111', data)
  372. datas.push(data)
  373. }
  374. return datas
  375. }
  376. const connect = async () => {
  377. const search = useOriginSearch()
  378. connentLoading.value = true
  379. const behaviorId = sessionStorage.getItem('behaviorId') || search.behaviorId || initBehaviorId
  380. const rate = runtime.speed / detailState.baseSpeed //1
  381. const content = {
  382. musicXmlInfos: formatTimes(),
  383. subjectId: detailState.subjectId ? detailState.subjectId : detailState.isPercussion ? 1 : detailState.subjectId,
  384. detailId: detailState.activeDetail?.id,
  385. examSongId: search.id,
  386. xmlUrl: detailState?.activeDetail?.xmlUrl,
  387. partIndex: detailState.partIndex,
  388. behaviorId,
  389. platform: 'WEB',
  390. clientId: 'STUDENT',
  391. hertz: SettingState.sett.hertz,
  392. feature: 'EVALUATION',
  393. practiceSource: (search.resourceType && search.resourceType === 'practice') ? 'UNIT_TEST_PRACTICE' : search.unitId ? 'UNIT_TEST' : 'PRACTICE',
  394. // 这里定义的是数字但是因为是通过input输入所以强制转化一次
  395. reactionTimeMs: parseFloat('' + SettingState.eva.reactionTimeMs) || 0,
  396. speed: runtime.speed,
  397. heardLevel: SettingState.eva.difficulty,
  398. // beatLength: Math.round((RuntimeUtils.getFixTime(detailState.times[0].beatSpeed) * 1000) / rate),
  399. beatLength: actualBeatLength,
  400. evaluationCriteria: getEvaluationCriteria(),
  401. }
  402. // console.log("🚀 ~ content:", content, rate)
  403. const clientType = useClientType()
  404. if (clientType === 'student') {
  405. content.clientId = 'STUDENT'
  406. } else if (clientType === 'teacher') {
  407. content.clientId = 'TEACHER'
  408. } else {
  409. content.clientId = 'BACKEND'
  410. }
  411. if (browserInfo.android) {
  412. content.platform = 'ANDROID'
  413. }
  414. if (browserInfo.ios) {
  415. content.platform = 'IOS'
  416. }
  417. const evt = await promisefiyPostMessage({
  418. api: 'startEvaluating',
  419. content: content,
  420. })
  421. if (evt?.content?.reson) {
  422. Toast.fail({
  423. message: evt?.content?.reson,
  424. })
  425. connentLoading.value = false
  426. throw evt
  427. }
  428. connentLoading.value = false
  429. }
  430. const sendOffsetTime = (offsetTime: number) => {
  431. postMessage(
  432. {
  433. api: 'proxyServiceMessage',
  434. content: {
  435. header: {
  436. commond: 'audioPlayStart',
  437. type: 'SOUND_COMPARE',
  438. },
  439. body: {
  440. offsetTime,
  441. },
  442. },
  443. },
  444. () => {
  445. backtime = 0
  446. }
  447. )
  448. }
  449. const cancelTheEvaluation = () => {
  450. const search = useOriginSearch()
  451. setTimeout(() => {
  452. postMessage({ api: 'endEvaluating', content: { musicScoreId: search.id } })
  453. playStatus.value = 'stop'
  454. RuntimeUtils.pause()
  455. RuntimeUtils.resetPlayStatus()
  456. RuntimeUtils.clearIntervalTimeline()
  457. RuntimeUtils.setCurrentTime(0)
  458. Toast.clear()
  459. }, 500);
  460. }
  461. const stopPlay = () => {
  462. console.log('调用stopPlay')
  463. if (!connentLoading.value) {
  464. cancelTheEvaluation()
  465. }
  466. startButtonShow.value = true
  467. connentLoading.value = false
  468. evaluating.value = false
  469. }
  470. export const evaluatStopPlay = stopPlay
  471. const startPlay = () => {
  472. console.log('连接服务成功,开始播放', new Date().getTime() - runtime.clickTime)
  473. // if (!SettingState.eva.mute) {
  474. // RuntimeUtils.changeAllMode()
  475. // } else {
  476. // RuntimeUtils.changeMode('background')
  477. // }
  478. startButtonShow.value = false
  479. RuntimeUtils.setPlayState()
  480. }
  481. const setPlayer = async () => {
  482. // 连接中,禁止重复连接
  483. if (connentLoading.value) return
  484. runtime.clickTime = new Date().getTime()
  485. RuntimeUtils.resetPlayStatus()
  486. if (detailState.isPauseRecording) {
  487. evaluating.value = false
  488. startPlay()
  489. return
  490. }
  491. detailState.evaluatings = {}
  492. const hint = Toast({
  493. duration: 0,
  494. message: '服务连接中...',
  495. type: 'loading',
  496. })
  497. try {
  498. await connect()
  499. startPlay()
  500. setTimeout(() => {
  501. console.log('关闭弹窗')
  502. Toast.clear()
  503. hint.close()
  504. }, 100)
  505. } catch (error) {
  506. runtime.evaluatingStatus = false
  507. Toast.clear()
  508. }
  509. }
  510. const togglePlay = () => {
  511. if (detailState.isPauseRecording) {
  512. evaluating.value = false
  513. startPlay()
  514. return
  515. }
  516. if (evaluating.value) {
  517. stopPlay()
  518. } else {
  519. setPlayer()
  520. }
  521. }
  522. const timeupdate = () => {
  523. console.log('播放事件被触发', playUrl.value, evaluating.value)
  524. if (playUrl.value) {
  525. const nowTime = new Date().getTime()
  526. // console.log('播放开始的时间', nowTime)
  527. // synced = true
  528. let time = runtime.audiosInstance?.audios[playUrl.value].currentTime
  529. // 只有选段模式,并且开始小节非第一小节时,才执行以下计算
  530. const sectionIdx = detailState.section.length ? detailState.section[0].i : 0
  531. if (unitTestData.isSelectMeasureMode && sectionIdx > 0 ) {
  532. time = time - detailState.section[0].time
  533. }
  534. console.log('已播放时长: ', time * 1000)
  535. console.log('不减掉已播放时间: ', nowTime - backtime)
  536. const delayTime = nowTime - backtime - time * 1000
  537. console.log('真正播放延迟', delayTime, time, unitTestData.isSelectMeasureMode, sectionIdx)
  538. // 蓝牙耳机延迟一点发送消息确保在录音后面
  539. setTimeout(() => {
  540. sendOffsetTime(delayTime)
  541. }, 220)
  542. }
  543. }
  544. /**
  545. * 播放器停止事件
  546. */
  547. const playerStop = () => {
  548. // alert('stop' + this.endloading)
  549. console.log('playerStop播放器停止事件', endloading.value)
  550. if (endloading.value) {
  551. return
  552. }
  553. playStatus.value = 'stop'
  554. endloading.value = true
  555. startButtonShow.value = true
  556. RuntimeUtils.resetPlayStatus()
  557. RuntimeUtils.clearIntervalTimeline()
  558. RuntimeUtils.setCurrentTime(0)
  559. Toast({
  560. duration: 0,
  561. message: '评分中...',
  562. type: 'loading',
  563. })
  564. setTimeout(() => {
  565. postMessage(
  566. {
  567. api: 'endEvaluating',
  568. content: {
  569. musicScoreId: useOriginSearch().id,
  570. },
  571. },
  572. (evt) => {
  573. console.log('调用endEvaluating结束', evt)
  574. endloading.value = false
  575. evaluating.value = false
  576. // RuntimeUtils.setCaptureMode()
  577. }
  578. )
  579. RuntimeUtils.endCapture()
  580. }, 500);
  581. }
  582. export const evaluatPlayerStop = playerStop
  583. const endevent = (evt: Event) => {
  584. // 如果是单元测验和课后训练 播放结束
  585. if (unitTestData.isSelectMeasureMode && playStatus.value === 'play') {
  586. playerStop()
  587. canSubmit.value = true
  588. return
  589. }
  590. if ((evt.target as HTMLAudioElement)?.src === playUrl.value && playStatus.value === 'play') {
  591. playerStop()
  592. canSubmit.value = true
  593. }
  594. if (detailState.isAppPlay) {
  595. playerStop()
  596. canSubmit.value = true
  597. }
  598. }
  599. /**正式开始评测 */
  600. const evaluatStart = () => {
  601. playStatus.value = 'play'
  602. if (detailState.isPauseRecording) {
  603. postMessage(
  604. {
  605. api: 'resumeRecording',
  606. },
  607. () => {
  608. evaluating.value = true
  609. detailState.isPauseRecording = false
  610. RuntimeUtils.setCaptureMode()
  611. }
  612. )
  613. return
  614. } else {
  615. RuntimeUtils.setCaptureMode()
  616. }
  617. console.log('开始录音', new Date().getTime())
  618. postMessage(
  619. {
  620. api: 'startRecording',
  621. content: {
  622. accompanimentState: SettingState.eva.mute ? 1 : 0
  623. }
  624. },
  625. () => {
  626. // console.log('开始录音app回调时间', Date.now())
  627. backtime = Date.now()
  628. evaluating.value = true
  629. if (detailState.activeDetail?.midiUrl) {
  630. console.log('midiUrl', detailState.activeDetail?.midiUrl)
  631. setTimeout(() => {
  632. sendOffsetTime(0)
  633. }, 220)
  634. }
  635. }
  636. )
  637. RuntimeUtils.startCapture()
  638. }
  639. /**
  640. * 酷乐秀活动接口,Url中有设置并且仅在学生端提评分交数据
  641. * 管乐团单元测验, url中有单元测验ID仅在学生端提评分交数据
  642. */
  643. const submitEvaluationScore = async (data: any) => {
  644. const search = useOriginSearch()
  645. if (search.unitId) {
  646. if (!canSubmit.value) {
  647. Toast('完整演奏结束才算测验分数!')
  648. return
  649. }
  650. (endResult.value as any)?.score && scoreList.push((endResult.value as any)?.score)
  651. /** 有单元测验时,存储分数缓存 */
  652. postMessage({
  653. api: 'setCache',
  654. content: {
  655. key: 'h5-orchestra-unit',
  656. value: JSON.stringify({
  657. musicId: search.id || '',
  658. unitId: search.unitId || '',
  659. questionId: search.questionId || '',
  660. score: canSubmit.value ? (endResult.value as any)?.score || 0 : 0,
  661. }),
  662. },
  663. })
  664. canSubmit.value = false
  665. }
  666. }
  667. /** 活动使用,只有在全部评测完成后才能提交,避免只是一小节就高分的情况 */
  668. const canSubmit = ref(false)
  669. /**接受websocket返回的信息 */
  670. const sendResult = (evt?: IPostMessage) => {
  671. const { body, header } = evt?.content || {}
  672. console.log('评测返回', body)
  673. if (body && header) {
  674. const data = evt?.content?.body
  675. if (evt?.content.header.commond === 'overall') {
  676. // console.log(evt)
  677. detailState.isHideEvaluatReportSaveBtn = false;
  678. Toast.clear()
  679. endResult.value = data
  680. evaluatingShow.value = true
  681. submitEvaluationScore(data)
  682. } else if (evt?.content.header.commond === 'checkDone') {
  683. // 此处已经在校音中单独监听不做处理
  684. } else if (evt?.content.header.commond === 'checking') {
  685. // 此处已经在校音中单独监听不做处理
  686. } else if (evt?.content.header.commond === "recordEnd") {
  687. if (delayData.checkStatus !== 'ing') return
  688. delayData.count++;
  689. if (delayData.count >= 2) {
  690. handleToggleTune('finishTune');
  691. return;
  692. }
  693. setTimeout(() => {
  694. startTune()
  695. }, 100)
  696. } else {
  697. const getBeforeNote = (index: number) => {
  698. while (index >= 0) {
  699. const item = detailState.times[index]
  700. if (item.stave) {
  701. return item
  702. }
  703. index--
  704. }
  705. }
  706. const setEvaluatings = (note: any, data: any, dontTransition = false) => {
  707. const startNote = getBoundingBoxByverticalNote(note)
  708. // console.log(detailState.evaluatings, startNote)
  709. detailState.evaluatings = {
  710. ...detailState.evaluatings,
  711. [startNote.measureIndex]: {
  712. ...startNote,
  713. ...getLeveByScoreMeasure(data.score),
  714. score: data.score,
  715. dontTransition,
  716. },
  717. }
  718. }
  719. for (let index = 0; index < detailState.times.length; index++) {
  720. let time = detailState.times[index]
  721. if (data.measureRenderIndex == time.noteElement.sourceMeasure.measureListIndex) {
  722. if (!time.stave) {
  723. const ntime = getBeforeNote(index)
  724. // console.log('ntime', ntime)
  725. if (ntime) {
  726. time = ntime
  727. }
  728. }
  729. if (!time.noteElement.tie) {
  730. setEvaluatings(time, data)
  731. } else {
  732. for (const item of time.noteElement.tie.notes) {
  733. const note = getParentNote(item)
  734. if (!note) continue
  735. setEvaluatings(
  736. note,
  737. data,
  738. item.NoteToGraphicalNoteObjectId !== time.noteElement.tie.StartNote?.NoteToGraphicalNoteObjectId
  739. )
  740. }
  741. }
  742. break
  743. }
  744. }
  745. }
  746. }
  747. }
  748. const onProgress = () => {
  749. // console.log(runtime.currentTimeNum, detailState.times[detailState.times.length - 1]?.time - 2, detailState.times)
  750. if (runtime.currentTimeNum >= detailState.times[detailState.times.length - 1]?.time - 2) {
  751. canSubmit.value = true
  752. }
  753. }
  754. const cloudMetronome = (evt: any) => {
  755. startButtonShow.value = true
  756. }
  757. /** 监听评测弹窗是否隐藏保存演奏按钮 */
  758. const hideComplexButton = (callback: CallBack, listen?: boolean) => {
  759. if (listen) {
  760. listenerMessage("hideComplexButton", callback);
  761. } else {
  762. removeListenerMessage("hideComplexButton", callback);
  763. }
  764. };
  765. // 隐藏存演奏按钮
  766. const handleComplexButton = (res?: IPostMessage) => {
  767. console.log('监听是否隐藏保存按钮', res)
  768. if (res?.content) {
  769. const { header, body } = res.content;
  770. detailState.isHideEvaluatReportSaveBtn = true
  771. }
  772. };
  773. // 离开之前再提交一次最高分数
  774. export const submitMaxScore = () => {
  775. const search = useOriginSearch()
  776. if (search.unitId && scoreList.length) {
  777. console.log('最高分',scoreList,Math.max(...scoreList))
  778. postMessage({
  779. api: 'setCache',
  780. content: {
  781. key: 'h5-orchestra-unit',
  782. value: JSON.stringify({
  783. musicId: search.id || '',
  784. unitId: search.unitId || '',
  785. questionId: search.questionId || '',
  786. score: Math.max(...scoreList),
  787. }),
  788. },
  789. })
  790. }
  791. }
  792. /**
  793. * 木管(长笛 萨克斯 单簧管)乐器一级的2、3、6测评要放原音音频
  794. * 铜管乐器一级的1a,1b,5,6测评要放原音音频
  795. */
  796. const getMusicMode = (): RuntimeUtils.IMode => {
  797. const muguan = [2, 4, 5, 6];
  798. const tongguan = [12, 13, 14, 15, 17];
  799. if (muguan.includes(detailState.subjectId) && (detailState.activeDetail?.examSongName || "").search(/[^\u0000-\u00FF](1-2|1-3|1-6)/gi) > -1) {
  800. return "music";
  801. }
  802. if (tongguan.includes(detailState.subjectId) && (detailState.activeDetail?.examSongName || "").search(/[^\u0000-\u00FF](1-1-1|1-1-2|1-5|1-6)/gi) > -1) {
  803. return "music";
  804. }
  805. if ([23, 113, 121].includes(detailState.subjectId)) {
  806. return "music";
  807. }
  808. return "background";
  809. };
  810. export default defineComponent({
  811. name: 'ColexiuButtonEvaluating',
  812. setup(props, { expose }) {
  813. onMounted(async () => {
  814. console.log('进入评测模块')
  815. if (!SettingState.eva.mute) {
  816. RuntimeUtils.changeAllMode();
  817. } else {
  818. RuntimeUtils.changeMode('background', 'all')
  819. }
  820. handleCheckEvaluatStatus()
  821. // 如果为单元测验和课后训练,不清楚选段数据
  822. if (!unitTestData.isSelectMeasureMode) {
  823. detailState.section = []
  824. detailState.sectionStatus = false
  825. }
  826. playUrl.value = runtime.songs.background || (runtime.songs.music as string)
  827. // runtime.audiosInstance?.audios[playUrl.value]?.addEventListener('play', timeupdate)
  828. // runtime.audiosInstance?.audios[playUrl.value]?.addEventListener('timeupdate', onProgress)
  829. // RuntimeUtils.event.on('next-click', playerStop)
  830. RuntimeUtils.event.on('ended', endevent)
  831. listenerMessage('sendResult', sendResult)
  832. // listenerMessage('cancelEvaluating', cancelTheEvaluation)
  833. listenerMessage('cloudTimeUpdae', onProgress)
  834. RuntimeUtils.event.on('tickDestroy', cloudMetronome)
  835. RuntimeUtils.event.on('tickEnd', evaluatStart)
  836. hideComplexButton(handleComplexButton, true);
  837. // 开始效验
  838. checkEvaluating()
  839. })
  840. onBeforeUnmount(() => {
  841. // runtime.audiosInstance?.audios[playUrl.value]?.removeEventListener('play', timeupdate)
  842. // runtime.audiosInstance?.audios[playUrl.value]?.removeEventListener('timeupdate', onProgress)
  843. // RuntimeUtils.event.off('next-click', playerStop)
  844. RuntimeUtils.event.off('ended', endevent)
  845. RuntimeUtils.event.off('tickDestroy', cloudMetronome)
  846. removeListenerMessage('sendResult', sendResult)
  847. // removeListenerMessage('cancelEvaluating', cancelTheEvaluation)
  848. removeListenerMessage('cloudTimeUpdae', onProgress)
  849. hideComplexButton(() => {}, false);
  850. RuntimeUtils.event.off('tickEnd', evaluatStart)
  851. submitMaxScore()
  852. })
  853. expose({
  854. setPlayer,
  855. startPlay,
  856. stopPlay,
  857. togglePlay,
  858. playerStop,
  859. evaluating,
  860. connentLoading,
  861. playStatus,
  862. cancelTheEvaluation,
  863. })
  864. return () => {
  865. return (
  866. <Teleport to="body" key="StartEvaluating">
  867. {/* 评测完成结果显示 */}
  868. <Evaluating data={endResult.value} />
  869. <Transition name="finish">
  870. {startButtonShow.value && (
  871. <div
  872. style={{
  873. backgroundImage: `url(${iconEvaluatingStart})`,
  874. 'transform': detailState.isSpecialShapedScreen ? `translateX(${detailState.notchHeight / 4}px)` : '',
  875. }}
  876. class={[styles.evaluatStartBtn]}
  877. onClick={() => {
  878. setPlayer()
  879. }}
  880. ></div>
  881. )}
  882. </Transition>
  883. {!evaluating.value ? (
  884. <div class={styles.dialogueBox} key="start">
  885. <div class={styles.dialogue}>
  886. <div>
  887. 演奏前请调整好乐器,保证最佳演奏状态。<span class={styles.triangle}></span>
  888. </div>
  889. </div>
  890. <Vue3Lottie class={styles.dialogueIcon} animationData={startData}></Vue3Lottie>
  891. </div>
  892. ) : (
  893. <div class={styles.dialogueBox} key="starting">
  894. <div class={styles.inRadio}>收音中...</div>
  895. <Vue3Lottie class={styles.inRadioIcon} animationData={startingData}></Vue3Lottie>
  896. </div>
  897. )}
  898. {/* 延迟检测窗口 */}
  899. <Popup
  900. teleport="body"
  901. class="popup-scale"
  902. transition="van-scale"
  903. overlay={false}
  904. show={delayData.open}
  905. onClose={() => handleCheckDelayEnd()}
  906. >
  907. <CheckDelayPopup
  908. delayData={delayData}
  909. onStartCheckDelay={() => handleStartCheckDelay()}
  910. onClose={() => handleStopCheckDelay()}
  911. />
  912. </Popup>
  913. </Teleport>
  914. )
  915. }
  916. },
  917. })