evaluating.tsx 32 KB

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