state.ts 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. import { closeToast, showToast } from "vant";
  2. import { nextTick, reactive } from "vue";
  3. import { OpenSheetMusicDisplay } from "../osmd-extended/src";
  4. import { metronomeData } from "./helpers/metronome";
  5. import { GradualNote, GradualTimes, GradualVersion } from "./type";
  6. import { handleEndEvaluat, handleStartEvaluat } from "./view/evaluating";
  7. import { IFingering, mappingVoicePart, subjectFingering, matchVoicePart } from "/src/view/fingering/fingering-config";
  8. import { handleStartTick } from "./view/tick";
  9. import { audioListStart, getAudioCurrentTime, getAudioDuration, setAudioCurrentTime, setAudioPlaybackRate, audioData } from "./view/audio-list";
  10. import { toggleFollow } from "./view/follow-practice";
  11. import { browser, setStorageSpeed, setGlobalData } from "./utils";
  12. import { api_cloudGetMediaStatus, api_createMusicPlayer, api_cloudChangeSpeed, api_cloudSuspend, api_cloudSetCurrentTime, api_cloudDestroy } from "./helpers/communication";
  13. import { verifyCanRepeat, getDuration } from "./helpers/formateMusic";
  14. import { getMusicSheetDetail } from "./utils/baseApi"
  15. import { getQuery } from "/src/utils/queryString";
  16. import { followData } from "/src/view/follow-practice/index"
  17. const query: any = getQuery();
  18. /** 入门 | 进阶 | 大师 */
  19. export type IDifficulty = "BEGINNER" | "ADVANCED" | "PERFORMER";
  20. /** 渲染类型: 五线谱,简谱 */
  21. export enum EnumMusicRenderType {
  22. /** 五线谱 */
  23. staff = "staff",
  24. /** 简谱 */
  25. firstTone = "firstTone",
  26. /** 固定音高 */
  27. fixedTone = "fixedTone",
  28. }
  29. export const musicscoresettingKey = "musicscoresetting";
  30. /** 有声音的是那个音源 */
  31. export type IPlayState = "music" | "background";
  32. /** 播放状态 */
  33. export type IAudioState = "play" | "paused";
  34. /** 来源 */
  35. export enum IPlatform {
  36. APP = "APP",
  37. PC = "PC",
  38. }
  39. export type ISonges = {
  40. background?: string
  41. music?: string
  42. }
  43. /**
  44. * 特殊教材分类id
  45. */
  46. const classids = [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 30, 31, 35, 36, 38, 108, 150, 151, 152, 153, 154, 155, 156, 157, 158, 178, 179, 180, 181, 182]; // 大雅金唐, 竖笛教程, 声部训练展开的分类ID
  47. // 乐器code码
  48. export const musicalInstrumentCodeInfo = [
  49. {
  50. name: '长笛',
  51. code: 'Flute',
  52. id: 1
  53. },
  54. {
  55. name: '短笛',
  56. code: 'Piccolo',
  57. id: 2
  58. },
  59. {
  60. name: '单簧管',
  61. code: 'Clarinet',
  62. id: 3
  63. },
  64. {
  65. name: '低音单簧管',
  66. code: 'Bass Clarinet',
  67. id: 4
  68. },
  69. {
  70. name: '中音萨克斯',
  71. code: 'Alto Saxophone',
  72. id: 5
  73. },
  74. {
  75. name: '次中音萨克斯',
  76. code: 'Tenor Saxophone',
  77. id: 6
  78. },
  79. {
  80. name: '高音萨克斯',
  81. code: 'Soprano Saxophone',
  82. id: 7
  83. },
  84. {
  85. name: '上低音萨克斯',
  86. code: 'Baritone Saxophone',
  87. id: 8
  88. },
  89. {
  90. name: '双簧管',
  91. code: 'Oboe',
  92. id: 9
  93. },
  94. {
  95. name: '大管',
  96. code: 'Bassoon',
  97. id: 10
  98. },
  99. {
  100. name: '小号',
  101. code: 'Trumpet',
  102. id: 11
  103. },
  104. {
  105. name: '圆号',
  106. code: 'Horn',
  107. id: 12
  108. },
  109. {
  110. name: '长号',
  111. code: 'Trombone',
  112. id: 13
  113. },
  114. {
  115. name: '上低音号',
  116. code: 'Baritone',
  117. id: 14
  118. },
  119. {
  120. name: '次中音号',
  121. code: 'Euphonium',
  122. id: 15
  123. },
  124. {
  125. name: '大号',
  126. code: 'Tuba',
  127. id: 16
  128. },
  129. {
  130. name: '钢琴',
  131. code: 'Piano',
  132. id: 17
  133. },
  134. {
  135. name: '电钢琴',
  136. code: 'Electronical Piano',
  137. id: 18
  138. },
  139. {
  140. name: '钢片琴',
  141. code: 'Glockenspiel',
  142. id: 19
  143. },
  144. {
  145. name: '小提琴',
  146. code: 'Violin',
  147. id: 20
  148. },
  149. {
  150. name: '中提琴',
  151. code: 'Viola',
  152. id: 21
  153. },
  154. {
  155. name: '大提琴',
  156. code: 'Violoncello',
  157. id: 22
  158. },
  159. {
  160. name: '低音提琴',
  161. code: 'Contrabass',
  162. id: 23
  163. },
  164. {
  165. name: '架子鼓',
  166. code: 'Drum Set',
  167. id: 24
  168. },
  169. {
  170. name: '小鼓',
  171. code: 'Snare Drum',
  172. id: 25
  173. },
  174. {
  175. name: '马林巴',
  176. code: 'Marimba',
  177. id: 26
  178. },
  179. {
  180. name: '颤音琴',
  181. code: 'Vibraphone',
  182. id: 27
  183. },
  184. {
  185. name: '钟琴',
  186. code: 'Chimes',
  187. id: 28
  188. },
  189. {
  190. name: '木琴',
  191. code: 'Xylophone',
  192. id: 29
  193. },
  194. {
  195. name: '管钟',
  196. code: 'Tubular Bells',
  197. id: 30
  198. },
  199. {
  200. name: '定音鼓',
  201. code: 'Timpani',
  202. id: 31
  203. },
  204. {
  205. name: '键盘',
  206. code: 'Mallets',
  207. id: 32
  208. },
  209. {
  210. name: '排箫',
  211. code: 'Panpipes',
  212. id: 33
  213. },
  214. {
  215. name: '陶笛',
  216. code: 'Ocarina',
  217. id: 34
  218. },
  219. {
  220. name: '葫芦丝',
  221. code: 'Woodwind',
  222. id: 35
  223. },
  224. {
  225. name: '口风琴',
  226. code: 'Nai',
  227. id: 36
  228. },
  229. {
  230. name: '德式竖笛',
  231. code: 'Tenor Recorder',
  232. id: 37
  233. },
  234. {
  235. name: '英式竖笛',
  236. code: 'Baroque Recorder',
  237. id: 38
  238. },
  239. {
  240. name: '高音陶笛',
  241. code: 'Whistling',
  242. id: 39
  243. },
  244. ]
  245. const state = reactive({
  246. /** 来源 : PC , app */
  247. platform: "" as IPlatform,
  248. appName: "" as "GYM" | "COLEXIU",
  249. musicRenderType: EnumMusicRenderType.staff as EnumMusicRenderType,
  250. /**曲谱是否渲染完成 */
  251. musicRendered: false,
  252. /** 当前曲谱数据ID, 和曲谱ID不一致 */
  253. detailId: "",
  254. /** 曲谱资源URL */
  255. xmlUrl: "",
  256. /** 声部ID */
  257. subjectId: 0 as number,
  258. trackId: 0 as string | number,
  259. /** 分类ID */
  260. categoriesId: 0,
  261. /** 分类名称 */
  262. categoriesName: "",
  263. /** 是否支持评测 */
  264. enableEvaluation: true,
  265. /** 是否支持转谱 */
  266. enableNotation: false,
  267. /** 曲谱ID */
  268. examSongId: "",
  269. /** 内容平台的曲谱ID,可能会和业务端的id不一样 */
  270. cbsExamSongId: "",
  271. /** 曲谱名称 */
  272. examSongName: "",
  273. /** 曲谱封面 */
  274. coverImg: "",
  275. /** 扩展字段 */
  276. extConfigJson: {} as any,
  277. /** 扩展样式字段 */
  278. extStyleConfigJson: {} as any,
  279. /** 是否开启节拍器(mp3节拍器) */
  280. isOpenMetronome: false,
  281. /** 是否显示指法 */
  282. isShowFingering: false,
  283. /** 原音 */
  284. music: "",
  285. /** 伴奏 */
  286. accompany: "",
  287. /** midiURL */
  288. midiUrl: "",
  289. /** 父分ID */
  290. parentCategoriesId: 0,
  291. /** 分类ID */
  292. musicSheetCategoriesId: 0,
  293. /** 各产品端的分类ID,(管乐迷、管乐团、酷乐秀、课堂乐器) */
  294. bizMusicCategoryId: 0,
  295. /** 资源类型: mp3 | midi */
  296. playMode: "MP3" as "MP3" | "MIDI",
  297. /** 设置的速度 */
  298. speed: 0,
  299. /** 曲谱音频正常的速度 */
  300. originSpeed: 0,
  301. /** 播放过程中显示的速度 */
  302. playIngSpeed: 0,
  303. /** 分轨名称 */
  304. track: "",
  305. /** 当前显示声部索引 */
  306. partIndex: 0,
  307. /** 是否需要节拍器 */
  308. needTick: false,
  309. /** 曲谱实例 */
  310. osmd: null as unknown as OpenSheetMusicDisplay,
  311. /**是否是特殊乐谱类型, 主要针对管乐迷 */
  312. isSpecialBookCategory: false,
  313. /** 播放状态 */
  314. playState: "paused" as IAudioState,
  315. /** 播放结束状态 */
  316. playEnd: false,
  317. /** 播放那个: 原音,伴奏 */
  318. playSource: "music" as IPlayState,
  319. /** 播放进度 */
  320. playProgress: 0,
  321. /** 激活的note index */
  322. activeNoteIndex: 0,
  323. /** 激活的小节 */
  324. activeMeasureIndex: 0,
  325. /** 选段状态 */
  326. sectionStatus: false,
  327. /** 选段数据 */
  328. section: [] as any[],
  329. /** 选段背景 */
  330. sectionBoundingBoxs: [] as any[],
  331. /** 开启选段预备 */
  332. isOpenPrepare: false,
  333. /** 选段预备 */
  334. sectionFirst: null as any,
  335. /** 音符数据 */
  336. times: [] as any[],
  337. /** 播放模式 */
  338. modeType: "practise" as "practise" | "follow" | "evaluating",
  339. /** 设置 */
  340. setting: {
  341. /** 效音提醒 */
  342. soundEffect: true,
  343. /** 护眼模式 */
  344. eyeProtection: false,
  345. /** 摄像头 */
  346. camera: false,
  347. /** 摄像头透明度 */
  348. cameraOpacity: 70,
  349. /** 循环播放 */
  350. repeatAutoPlay: true,
  351. /** 显示指法 */
  352. displayFingering: true,
  353. /** 显示光标 */
  354. displayCursor: true,
  355. /** 频率 */
  356. frequency: 0,
  357. /** 评测难度 */
  358. evaluationDifficulty: "BEGINNER" as IDifficulty,
  359. /** 保存到相册 */
  360. saveToAlbum: true,
  361. /** 开启伴奏 */
  362. enableAccompaniment: true,
  363. /** 反应时间 */
  364. reactionTimeMs: 0,
  365. /** 节拍器音量 */
  366. beatVolume: 50,
  367. },
  368. /** 后台设置的基准评测频率 */
  369. baseFrequency: 440,
  370. /** mp3节拍器的时间,统计拍数、速度计算得出,evxml通过读取xml元素获取 */
  371. fixtime: 0,
  372. /** evxml等待播放的时间 */
  373. evXmlBeginTime: 0,
  374. /** 指法信息 */
  375. fingeringInfo: {} as IFingering,
  376. /** 滚动容器的ID */
  377. scrollContainer: "musicAndSelection",
  378. /** 是否是打击乐 */
  379. isPercussion: false,
  380. /** 评测标准 */
  381. evaluationStandard: '',
  382. /** 是否重复节拍器的时间 */
  383. repeatedBeats: 0,
  384. /**当前曲谱中所有声部名字 */
  385. partListNames: [] as any,
  386. /** 渐变速度信息 */
  387. gradual: [] as GradualNote[],
  388. /** 渐变速度版本 */
  389. gradualVersion: GradualVersion.BASE as GradualVersion,
  390. /** 渐变时间信息 */
  391. gradualTimes: null as GradualTimes,
  392. /** 单声部多声轨 */
  393. multitrack: 0,
  394. /** 缩放 */
  395. zoom: 0.8,
  396. /** 渲染曲谱比例 */
  397. musicZoom: 1,
  398. /** 练习,评测是否是选段模式 */
  399. isSelectMeasureMode: false,
  400. /** 是否是评分显示 */
  401. isReport: false,
  402. /** 是否隐藏评测报告弹窗,保存演奏按钮,默认不隐藏 */
  403. isHideEvaluatReportSaveBtn: false,
  404. /** 是否是合奏 */
  405. isConcert: false,
  406. /** 用户选择的结束小节数 */
  407. userChooseEndIndex: 0,
  408. /** 重播小节集合信息 */
  409. repeatInfo: [] as any,
  410. /** 多分轨的曲子,可支持筛选的分轨 */
  411. canSelectTracks: [] as any,
  412. /** 声部codeId */
  413. subjectCodeId: 0 as number,
  414. /** 乐器codeId,用于匹配乐器指法、声部转调、特殊声部处理等 */
  415. musicalCodeId: 0 as number,
  416. /** 乐器code,用于评测传参 */
  417. musicalCode: '' as any,
  418. /** 合奏曲目是否合并展示 */
  419. isCombineRender: false,
  420. /** 小节的持续时长,以后台设置的播放速度计算 */
  421. measureTime: 0,
  422. /** 跟练模式,节拍器播放的时间 */
  423. beatStartTime: 0,
  424. /** 是否为详情预览模式 */
  425. isPreView: false,
  426. /** 是否为评测报告模式 */
  427. isEvaluatReport: false,
  428. /** midi播放器是否初始化中 */
  429. midiPlayIniting: false,
  430. /** 曲目信息 */
  431. songs: {} as ISonges,
  432. isAppPlay: false, // 是否midi音频,midi是app播放
  433. /** 音频播放器实例 */
  434. audiosInstance: null as any,
  435. /** midi音频的时长 */
  436. durationNum: 0,
  437. midiSectionStart: 0,
  438. /** 音频文件是否加载完成 */
  439. audioDone: false,
  440. /** 谱面svgdom节点 */
  441. osmdSvgDom: null as any,
  442. /** 滚动容器dom */
  443. osdmScrollDom: null as any,
  444. /** 光标dom */
  445. cursorDom: null as any,
  446. fistNoteLeft: 0,
  447. /** 是否为单行谱渲染模式 */
  448. isSingleLine: false,
  449. /** 首尾音符的间距 */
  450. noteDistance: 0,
  451. /** 一行谱运动模式,平滑移动、匀速移动 */
  452. moveType: "smooth" as "smooth" | "uniform",
  453. /** 是否是evxml */
  454. isEvxml: false,
  455. noTimes: [] as any,
  456. attendHideMenu: true,
  457. /** 老师端:功能按钮布局方向 */
  458. playBtnDirection: "left" as "left" | "right",
  459. /** 云练习按钮方向,如果有指法并且是竖向的指法,为了防止播放按钮把指法挡住,此时云练习播放按钮方向应该取反 */
  460. musicScoreBtnDirection: "right" as "left" | "right",
  461. /** 是否在老师端上课页面 */
  462. isAttendClass: false,
  463. /** 引导页信息 */
  464. guideInfo: null as any,
  465. noteCoords: [] as any,
  466. specialPosInit: false,
  467. /** 资源类型 */
  468. paymentType: null,
  469. /** 播放模式,默认练习模式 */
  470. defaultModeType: 1,
  471. });
  472. const browserInfo = browser();
  473. let offset_duration = 0;
  474. /** 自定义数据 */
  475. export const customData = reactive({
  476. /** 自定义音符时值 */
  477. customNoteRealValue: [] as any,
  478. /** 自定义音符按读取到的时值 */
  479. customNoteCurrentTime: false,
  480. });
  481. /** 在渲染前后计算光标应该走到的音符 */
  482. const setStep = () => {
  483. // console.log('播放状态',state.playState)
  484. if (state.playState !== "play") {
  485. console.log("暂停播放");
  486. return;
  487. }
  488. let startTime = Date.now();
  489. requestAnimationFrame(() => {
  490. const endTime = Date.now();
  491. // 渲染时间大于16.6,就会让页面卡顿, 如果渲染时间大与16.6就下一个渲染帧去计算
  492. if (endTime - startTime < 16.7) {
  493. handlePlaying();
  494. setStep();
  495. } else {
  496. setTimeout(() => {
  497. handlePlaying();
  498. setStep();
  499. }, 16.7);
  500. }
  501. });
  502. };
  503. /** 开始播放 */
  504. export const onPlay = () => {
  505. console.log("开始播放");
  506. state.playEnd = false;
  507. // offset_duration = browserInfo.xiaomi ? 0.2 : 0.08;
  508. offset_duration = 0.2;
  509. setStep();
  510. };
  511. /** 播放模式结束自动重播 */
  512. const autoResetPlay = () => {
  513. if (state.modeType !== "practise") return;
  514. skipNotePlay(0, true);
  515. // 没有开启自动重播, 不是练习模式
  516. if (!state.setting.repeatAutoPlay) return;
  517. scrollViewNote();
  518. setTimeout(() => {
  519. togglePlay("play");
  520. }, 1000);
  521. };
  522. /** 播放完成事件 */
  523. export const onEnded = () => {
  524. console.log("音频播放结束");
  525. // if (state.isAppPlay) {
  526. // // 销毁播放器
  527. // api_cloudDestroy();
  528. // }
  529. // 修改状态为结束
  530. state.playEnd = true;
  531. state.playState = "paused";
  532. // 结束播放
  533. audioListStart(state.playState);
  534. // 调用结束评测
  535. handleEndEvaluat(true);
  536. // 调用自动重复播放
  537. autoResetPlay();
  538. };
  539. /**
  540. * 播放一直触发的事件
  541. */
  542. const handlePlaying = () => {
  543. const currentTime = getAudioCurrentTime();
  544. const duration = getAudioDuration();
  545. state.playProgress = (currentTime / duration) * 100;
  546. let item = getNote(currentTime);
  547. // console.log(11111,currentTime,duration,state.playSource, item)
  548. // console.log(item.i,item.noteId,item.measureSpeed)
  549. // 练习模式下,实时刷新小节速度
  550. if (item && state.modeType === "practise" && state.playState === "play" && item.measureSpeed && item.measureSpeed !== state.playIngSpeed) {
  551. const ratio = state.speed / state.originSpeed
  552. state.playIngSpeed = Math.ceil(ratio * item.measureSpeed) || state.speed
  553. } else if (state.modeType === "practise" && state.playState === "play" && item && !item.measureSpeed) {
  554. state.playIngSpeed = state.speed
  555. }
  556. if (item) {
  557. // 选段状态下
  558. if (state.sectionStatus && state.section.length === 2) {
  559. // 如果开启了预备拍
  560. const selectStartItem = state.sectionFirst ? state.sectionFirst : state.section[0];
  561. const selectEndItem = state.section[1];
  562. /**
  563. * #9374,反复小节的曲目播放错误, bug修复
  564. * 曲目:噢!苏珊娜-排箫-人音
  565. * 现象:重播小节为2-9,选段为4-12,当播完第9小节后会回到第2小节重播2-8,再播放10-12
  566. * 4-12,不符合重播规则,所以播完第9小节后,音频需要跳转到第10小节播放
  567. */
  568. if (state.repeatInfo.length) {
  569. const canRepeatInfo = verifyCanRepeat(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  570. const repeatIdx = canRepeatInfo.repeatIdx == -1 ? 0 : canRepeatInfo.repeatIdx
  571. if (state.modeType === "practise" && !canRepeatInfo.canRepeat && state.section[1].MeasureNumberXML > state.repeatInfo[repeatIdx].end) {
  572. const preItem = state.times[item.i - 1]
  573. if (preItem && preItem.MeasureNumberXML > item.MeasureNumberXML) {
  574. const skipItem = state.times.find((item: any) => item.MeasureNumberXML === preItem.MeasureNumberXML + 1)
  575. if (skipItem) {
  576. // 跳转到指定的音频位置
  577. setAudioCurrentTime(skipItem.time, skipItem.i);
  578. gotoNext(skipItem);
  579. return
  580. }
  581. }
  582. }
  583. }
  584. // if (Math.abs(selectEndItem.endtime - currentTime) < offset_duration) {
  585. // if (currentTime - selectEndItem.endtime > offset_duration) {
  586. //console.log(currentTime,selectEndItem.endtime)
  587. if (currentTime - selectEndItem.endtime >= 0) {
  588. console.log("选段播放结束", state.setting.repeatAutoPlay);
  589. // 如果为选段评测模式
  590. if (state.modeType === "evaluating" && state.isSelectMeasureMode) {
  591. onEnded();
  592. return;
  593. }
  594. // #8698 bug修复
  595. if (state.modeType === "practise" && state.sectionStatus) {
  596. onEnded();
  597. resetPlaybackToStart();
  598. return;
  599. }
  600. item = selectStartItem;
  601. setAudioCurrentTime(selectStartItem.time, selectStartItem.i);
  602. }
  603. }
  604. gotoNext(item);
  605. }
  606. // 评测不播放叮咚节拍器
  607. // if (state.modeType !== "evaluating") {
  608. // metronomeData.metro?.sound(currentTime);
  609. // }
  610. metronomeData.metro?.sound(currentTime);
  611. // 一行谱,需要滚动小节
  612. if (state.isSingleLine) {
  613. if (state.moveType === 'smooth') {
  614. smoothMoveSvgDom();
  615. } else {
  616. uniformMoveSvgDom();
  617. }
  618. }
  619. };
  620. /** 跳转到指定音符开始播放 */
  621. export const skipNotePlay = async (itemIndex: number, isStart = false) => {
  622. const item = state.times[itemIndex];
  623. let itemTime = item.time;
  624. if (isStart) {
  625. itemTime = 0;
  626. }
  627. if (item) {
  628. setAudioCurrentTime(itemTime, itemIndex);
  629. // 一行谱,点击音符,或者播放完成,需要跳转音符位置
  630. gotoNext(item, true);
  631. metronomeData.metro?.sound(itemTime);
  632. if (state.isAppPlay) {
  633. await api_cloudSetCurrentTime({
  634. currentTime: itemTime * 1000,
  635. songID: state.examSongId,
  636. })
  637. audioData.progress = itemTime
  638. state.midiSectionStart = itemTime
  639. }
  640. }
  641. };
  642. /**
  643. * 切换曲谱播放状态
  644. * @param playState 可选: 默认 undefined, 需要切换的状态 play:播放, paused: 暂停
  645. */
  646. export const togglePlay = async (playState?: "play" | "paused", sourceType?: string) => {
  647. // 如果mp3资源还在加载中,给出提示
  648. if (!state.isAppPlay && !state.audioDone) {
  649. if (sourceType !== 'courseware') showToast('音频资源加载中,请稍后')
  650. return
  651. }
  652. // midi播放
  653. if (state.isAppPlay) {
  654. if (playState === "paused") {
  655. await api_cloudSuspend({
  656. songID: state.examSongId,
  657. })
  658. state.playState = 'paused'
  659. return
  660. }
  661. skipNotePlay(state.activeNoteIndex, false);
  662. await api_cloudChangeSpeed({
  663. speed: state.modeType === "evaluating" ? state.originSpeed : state.speed,
  664. originalSpeed: state.originSpeed,
  665. songID: state.examSongId,
  666. });
  667. const cloudGetMediaStatus = await api_cloudGetMediaStatus();
  668. const status = cloudGetMediaStatus?.content.status === "suspend" ? "play" : "paused"
  669. state.playState = status
  670. } else {
  671. state.playState = playState ? playState : state.playState === "paused" ? "play" : "paused";
  672. }
  673. if (state.playState === "play" && state.sectionStatus && state.section.length == 2 && state.playProgress === 0) {
  674. resetPlaybackToStart();
  675. }
  676. // 设置为开始播放时, 如果需要节拍,先播放节拍器
  677. if (state.playState === "play" && state.needTick) {
  678. const tickend = await handleStartTick();
  679. // console.log("🚀 ~ tickend:", tickend)
  680. // 节拍器返回false, 取消播放
  681. if (!tickend) {
  682. state.playState = "paused";
  683. return false;
  684. }
  685. }
  686. // 如果选段没有结束, 直接开始播放,清空选段状态
  687. if (state.playState == "play") {
  688. if (state.sectionStatus && state.section.length < 2) {
  689. clearSelection();
  690. }
  691. }
  692. audioListStart(state.playState);
  693. return true;
  694. };
  695. /** 结束播放 */
  696. export const handleStopPlay = () => {
  697. state.playState = "paused";
  698. audioListStart(state.playState);
  699. };
  700. /** 重置播放为开始 */
  701. export const resetPlaybackToStart = () => {
  702. // 如果为选段状态
  703. if (state.sectionStatus && state.section.length === 2) {
  704. state.section = formateSelectMearure(state.section);
  705. return;
  706. } else {
  707. // 非选段状态,重播需要重置当前选中的小节为第一个小节
  708. metronomeData.activeMetro = metronomeData.metroMeasure[0]?.[0] || {};
  709. }
  710. skipNotePlay(0, true);
  711. };
  712. /** 跳转到指定音符 */
  713. export const gotoCustomNote = (index: number) => {
  714. try {
  715. state.osmd.cursor.reset();
  716. } catch (error) { }
  717. for (let i = 0; i < index; i++) {
  718. state.osmd.cursor.next();
  719. }
  720. };
  721. // 找出离目标元素最近的音符
  722. const computedDistance = (x: number, y: number) => {
  723. let minDistance = -1, minidx = 0;
  724. let a, b, c;
  725. state.noteCoords.forEach((note: any, idx: any) => {
  726. //a,b为直角三角形的两个直角边
  727. a = Math.abs(note.x - x)
  728. b = Math.abs(note.y - y)
  729. //c为直角三角形的斜边
  730. c = Math.sqrt(a * a + b * b) as 0
  731. c = Number(c.toFixed(0)) as 0
  732. if (c !== 0 && (minDistance === - 1 || c < minDistance)) {
  733. //min为元素中离目标元素最近元素的距离
  734. minDistance = c
  735. minidx = idx
  736. }
  737. })
  738. return minidx
  739. };
  740. const customNotePosition = (note: any, cursor: any) => {
  741. const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
  742. if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
  743. const pageLeft = document.getElementById('scrollContainer')?.getBoundingClientRect()?.x || 0;
  744. // 元素的位置
  745. const element = document.getElementById('cursorImg-0')?.getBoundingClientRect?.() || { x: 0, y: 0 };
  746. // 找出距离元素最近的音符
  747. if (element.x && element.y) {
  748. const noteIdx = computedDistance(element.x, element.y);
  749. const targetX = state.noteCoords[noteIdx]?.x - pageLeft;
  750. console.log('音符索引', noteIdx)
  751. cursor.cursorElement.style.left = targetX + "px";
  752. cursor.cursorElement.style.transform = `translateX(0px)`;
  753. }
  754. }
  755. }
  756. const setCursorPosition = (note: any, cursor: any, flag?: string) => {
  757. // console.log('音符',note?.i,state.osmd.Cursor.noteGraphicalId,note.svgElement?.attrs?.id)
  758. if (state.musicRenderType === EnumMusicRenderType.firstTone || state.musicRenderType === EnumMusicRenderType.fixedTone) {
  759. /**
  760. * bug:#9920、#9940
  761. * 简谱选段模式,预备小节为休止小节时,选段播放结束,指针会重置到第一小节位置的初始位置
  762. */
  763. if (state.sectionStatus && state.playState === 'paused' && state.sectionFirst && (note.multipleRestMeasures || note.MeasureNumberXML !== state.sectionFirst?.MeasureNumberXML)) {
  764. return
  765. }
  766. const specialIds = ['1788850864767643649', '1788502467554750466', '1788501975122489346'];
  767. if (specialIds.includes(state.cbsExamSongId) && note.multipleRestMeasures === 0) {
  768. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  769. const cursorLeft = cursor?.cursorElement?.style?.left ? parseFloat(cursor.cursorElement.style.left) : 0;
  770. let patchX = 0;
  771. if (state.cbsExamSongId == '1788502467554750466') {
  772. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  773. patchX = (note.i == 0 || note.i == 60) ? 21 : (note.i == 1 || note.i == 7 || note.i == 23 || note.i == 38 || note.i == 44 || note.i == 52 || note.i == 58) ? -6 : (note.i >= 2 || note.i <= 6) || (note.i >= 8 || note.i <= 22) || (note.i >= 24 || note.i <= 37) || (note.i >= 39 || note.i <= 43) || (note.i >= 45 || note.i <= 51) || (note.i >= 53 || note.i <= 57) || (note.i == 59) ? 6 : 0;
  774. }
  775. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  776. patchX = note.i == 0 ? 31 : (note.i == 8 || note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59 || note.i == 65) ? -10 : note.i == 67 ? 31 : 0;
  777. }
  778. } else if (state.cbsExamSongId == '1788501975122489346') {
  779. if (state.musicRenderType === EnumMusicRenderType.firstTone) {
  780. patchX = (note.i == 0) ? 21 : (note.i == 1 || note.i == 7 || note.i == 23 || note.i == 38 || note.i == 44 || note.i == 52 || note.i == 58) ? -6 : (note.i == 9 || note.i == 10 || note.i == 12 || note.i == 13) ? 3 : (note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59) ? 6 : (note.i == 45) ? -8 : (note.i >= 15 || note.i <= 29) || (note.i >= 31 || note.i <= 36) || (note.i >= 38 || note.i <= 44) || (note.i >= 46 || note.i <= 50) || (note.i >= 52 || note.i <= 58) || (note.i >= 60 || note.i <= 64) || (note.i == 66) ? 4 : 0;
  781. }
  782. if (state.musicRenderType === EnumMusicRenderType.fixedTone) {
  783. patchX = note.i == 0 ? 31 : (note.i == 8 || note.i == 14 || note.i == 30 || note.i == 45 || note.i == 51 || note.i == 59 || note.i == 65) ? -10 : note.i == 67 ? 31 : 0;
  784. }
  785. }
  786. if (flag === 'refresh' || (flag === 'init' && !state.specialPosInit)) {
  787. // console.log('音符idx',note?.i,cursor.cursorElement.style.left)
  788. cursor.cursorElement.style.left = cursorLeft + patchX + "px";
  789. state.specialPosInit = true;
  790. }
  791. } else {
  792. nextTick(() => {
  793. let bbox = note.bbox;
  794. if (!bbox) {
  795. const musicContainer = document.getElementById("musicAndSelection")?.getBoundingClientRect() || {
  796. x: 0,
  797. y: 0,
  798. };
  799. const parentLeft = musicContainer.x || 0;
  800. const noteEle = document.querySelector(`#vf-${note.svgElement?.attrs?.id}`);
  801. if (noteEle) {
  802. const noteHead = noteEle.querySelector(".vf-numbered-note-head");
  803. const noteHeadBbox = noteHead?.getBoundingClientRect?.();
  804. if (noteHeadBbox) {
  805. note.bbox = {
  806. left: noteHeadBbox.x - parentLeft - noteHeadBbox.width / 4,
  807. width: noteHeadBbox.width * 1.5,
  808. };
  809. bbox = note.bbox;
  810. }
  811. }
  812. }
  813. if (!bbox) return;
  814. const baseW = state.platform === IPlatform.PC ? 29 : 18;
  815. const width = (bbox.width - baseW) / 3;
  816. // console.log(555555,bbox.left,width)
  817. cursor.cursorElement.style.left = bbox.left + "px";
  818. cursor.cursorElement.style.transform = `translateX(${width}px)`;
  819. });
  820. }
  821. }
  822. };
  823. /**
  824. * 跳转到下一个音符
  825. * 一行谱,点击音符,或者播放完成,需要跳转音符位置,增加参数skipNote
  826. **/
  827. export const gotoNext = (note: any, skipNote?: boolean) => {
  828. // console.log(33333333333,state.activeNoteIndex,note.i)
  829. const num = note.i;
  830. if (state.activeNoteIndex === note.i) {
  831. try {
  832. setCursorPosition(note, state.osmd.cursor, 'init');
  833. } catch (error) {
  834. console.log(error);
  835. }
  836. return;
  837. }
  838. const osmd = state.osmd;
  839. let prev = state.activeNoteIndex;
  840. state.activeNoteIndex = num;
  841. state.activeMeasureIndex = note.MeasureNumberXML;
  842. if (prev && num - prev === 1) {
  843. // console.log('跳转音符',11111,osmd.cursor)
  844. // if (!note.id && note.multipleRestMeasures === 0) {
  845. // } else {
  846. // osmd.cursor.next();
  847. // }
  848. osmd.cursor.next();
  849. } else if (prev && num - prev > 0) {
  850. while (num - prev > 0) {
  851. prev++;
  852. // console.log('跳转音符',22222)
  853. osmd.cursor.next();
  854. }
  855. } else {
  856. gotoCustomNote(num);
  857. }
  858. try {
  859. setCursorPosition(note, state.osmd.cursor, 'refresh');
  860. } catch (error) {
  861. console.log(error);
  862. }
  863. // 一行谱,需要滚动小节
  864. if (state.isSingleLine) {
  865. moveSvgDom(skipNote);
  866. }
  867. scrollViewNote();
  868. };
  869. /** 获取指定音符 */
  870. export const getNote = (currentTime: number) => {
  871. const times = state.times;
  872. const len = state.times.length;
  873. /** 播放超过了最后一个音符的时间,直接结束, 2秒误差 */
  874. if (currentTime > times[len - 1].endtime + 2 && !state.isAppPlay) {
  875. onEnded();
  876. return;
  877. }
  878. let _item = null as any;
  879. for (let i = state.activeNoteIndex; i < len; i++) {
  880. const item = times[i];
  881. const prevItem = times[i - 1];
  882. if (currentTime >= item.time) {
  883. if (!prevItem || item.time != prevItem.time) {
  884. _item = item;
  885. }
  886. } else {
  887. break;
  888. }
  889. }
  890. // console.log("activeNoteIndex", currentTime, state.activeNoteIndex, _item.i);
  891. return _item;
  892. };
  893. /** 重播 */
  894. export const handleResetPlay = () => {
  895. // 如果是midi需要重置播放进度
  896. if (state.isAppPlay) {
  897. audioData.progress = 0
  898. }
  899. resetPlaybackToStart();
  900. // 如果是暂停, 直接播放
  901. togglePlay("play");
  902. };
  903. /** 设置速度 */
  904. export const handleSetSpeed = (speed: number) => {
  905. setStorageSpeed(state.examSongId, speed);
  906. state.speed = speed;
  907. };
  908. /** 清除选段状态 */
  909. export const clearSelection = () => {
  910. state.sectionStatus = false;
  911. state.section = [];
  912. closeToast();
  913. };
  914. /** 开启选段 */
  915. export const handleChangeSection = () => {
  916. // 如果开启了选段,再次点击取消选段
  917. if (state.sectionStatus) {
  918. togglePlay("paused");
  919. clearSelection();
  920. skipNotePlay(0, true);
  921. state.sectionFirst = null;
  922. return;
  923. }
  924. state.sectionStatus = true;
  925. // 开启
  926. if (state.sectionStatus) {
  927. togglePlay("paused");
  928. }
  929. showToast({
  930. message: "请选择开始小节",
  931. duration: 0,
  932. position: "top",
  933. className: "selectionToast",
  934. });
  935. };
  936. /** 效验并格式化选段小节 */
  937. const formateSelectMearure = (_list: any[]): any[] => {
  938. if (!_list.length) return [];
  939. const list = _list.sort((a, b) => a.time - b.time);
  940. const startXml = list[0]?.measureOpenIndex;
  941. const endXml = list.last()?.measureOpenIndex;
  942. const selectStartMeasure = state.times.filter((n: any) => startXml === n.measureOpenIndex) || [];
  943. const selectEndMeasure = state.times.filter((n: any) => endXml === n.measureOpenIndex) || [];
  944. // 没有找到选段小节
  945. if (!selectStartMeasure.length || !selectEndMeasure.length) {
  946. clearSelection();
  947. return [];
  948. }
  949. list[0] = selectStartMeasure[0];
  950. list[1] = selectEndMeasure.last();
  951. let startItemINdex = list[0].i;
  952. // 开启预备拍
  953. if (state.isOpenPrepare) {
  954. const startXmlIndex = list[0].MeasureNumberXML;
  955. state.sectionFirst = state.times.find((n: any) => startXmlIndex - n.MeasureNumberXML === 1);
  956. startItemINdex = state.sectionFirst ? state.sectionFirst.i : startItemINdex;
  957. }
  958. skipNotePlay(startItemINdex, startItemINdex === 0);
  959. return list;
  960. };
  961. /** 选择选段 */
  962. export const handleSelection = (item: any) => {
  963. if (!state.sectionStatus || state.section.length > 1) return;
  964. if (state.section.length !== 2 && item) {
  965. state.section.push(item);
  966. if (state.section.length === 2) {
  967. setSection(state.section[0].MeasureNumberXML, state.section[1].MeasureNumberXML)
  968. //state.section = formateSelectMearure(state.section);
  969. closeToast();
  970. }
  971. }
  972. if (state.section.length === 1) {
  973. showToast({
  974. message: "请选择结束小节",
  975. duration: 0,
  976. position: "top",
  977. className: "selectionToast",
  978. });
  979. }
  980. };
  981. /** 阶段练习、阶段评测设置选段小节 */
  982. export const setSection = (start: number, end: number, userSpeed?: number) => {
  983. const startNotes = state.times.filter(
  984. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == start
  985. )
  986. const endNotes = state.times.filter(
  987. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == end
  988. )
  989. state.userChooseEndIndex = end
  990. const lastEndId = endNotes[endNotes.length - 1].noteId
  991. let lastEndNotes = endNotes.filter((n: any) => n.noteId === lastEndId)
  992. // 是否符合重播规则
  993. const canRepeatInfo = verifyCanRepeat(start, end)
  994. console.log('能否重播', canRepeatInfo)
  995. const isCanRepeat = canRepeatInfo.canRepeat
  996. // 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  997. /**
  998. * 如果符合重播规则,但是lastEndNotes长度为1,则需要向前找,直到找到lastEndNotes长度为2
  999. * 2024.03.28 新增逻辑,如果当前选中的结束小节是跳房子,则不向前找,因为这种场景不符合重播规则(bug:#9921)
  1000. * TODO:通过vf-volta判断是否是跳房子
  1001. */
  1002. let isSkipVolta = false; // 结束小节是否是跳房子小节
  1003. if (lastEndNotes.length === 1) {
  1004. isSkipVolta = lastEndNotes[0]?.stave?.modifiers?.some((item: any) => item.getAttribute('type') === 'Volta')
  1005. }
  1006. let currentEndNum: number = end
  1007. const lastEndIndex: any = state.repeatInfo[canRepeatInfo.repeatIdx]?.end || 0
  1008. while (isCanRepeat && lastEndNotes.length === 1 && lastEndNotes[0].MeasureNumberXML <= lastEndIndex && !isSkipVolta) {
  1009. currentEndNum = currentEndNum - 1
  1010. const newEndNotes = state.times.filter(
  1011. (n: any) => n.noteElement.sourceMeasure.MeasureNumberXML == currentEndNum
  1012. )
  1013. const newLastEndId = newEndNotes[newEndNotes.length - 1].noteId
  1014. lastEndNotes = newEndNotes.filter((n: any) => n.noteId === newLastEndId)
  1015. }
  1016. const endIdx: any = (isCanRepeat && canRepeatInfo.repeatIdx == state.repeatInfo.length - 1) ? lastEndNotes.length - 1 : 0
  1017. const startNote = startNotes[0]
  1018. // const endNote = endNotes[endNotes.length - 1]
  1019. const endNote = lastEndNotes[endIdx]
  1020. if (startNote && endNote) {
  1021. state.isSelectMeasureMode = true;
  1022. // 设置小节
  1023. hanldeDirectSelection([startNote, endNote]);
  1024. //设置速度
  1025. if (userSpeed) {
  1026. handleSetSpeed(userSpeed);
  1027. }
  1028. }
  1029. }
  1030. /** 直接设置选段 */
  1031. export const hanldeDirectSelection = (list: any[]) => {
  1032. if (!Array.isArray(list) || list.length !== 2) return;
  1033. state.sectionStatus = true;
  1034. setTimeout(() => {
  1035. state.section = formateSelectMearure(list);
  1036. console.log('选段小节', state.section)
  1037. }, 500);
  1038. };
  1039. let offsetTop = 0;
  1040. /**
  1041. * 窗口内滚动到音符的区域
  1042. * @param isScroll 可选: 强制滚动到顶部, 默认: false
  1043. * @returns void
  1044. */
  1045. export const scrollViewNote = () => {
  1046. const cursorElement = document.getElementById("cursorImg-0")!;
  1047. const musicAndSelection = document.getElementById(state.scrollContainer)!;
  1048. if (!cursorElement || !musicAndSelection || offsetTop === cursorElement.offsetTop) return;
  1049. offsetTop = cursorElement.offsetTop;
  1050. if (offsetTop > 50) {
  1051. musicAndSelection.scrollTo({
  1052. top: (offsetTop - 50) * state.musicZoom,
  1053. behavior: "smooth",
  1054. });
  1055. } else {
  1056. musicAndSelection.scrollTo({
  1057. top: 0,
  1058. behavior: "smooth",
  1059. });
  1060. }
  1061. };
  1062. /** 检测是否是节奏练习 */
  1063. export const isRhythmicExercises = () => {
  1064. return state.examSongName.indexOf("节奏练习") > -1;
  1065. };
  1066. /** 重置状态 */
  1067. export const handleRessetState = () => {
  1068. // 切换模式,清除选段
  1069. clearSelection();
  1070. skipNotePlay(0, true);
  1071. // midi 重置播放进度
  1072. if (state.isAppPlay) {
  1073. audioData.progress = 0;
  1074. }
  1075. if (state.modeType === "evaluating") {
  1076. handleStartEvaluat();
  1077. } else if (state.modeType === "practise") {
  1078. togglePlay("paused");
  1079. } else if (state.modeType === "follow") {
  1080. toggleFollow(false);
  1081. }
  1082. };
  1083. export default state;
  1084. /** 初始化评测音频 */
  1085. export const evaluatCreateMusicPlayer = () => {
  1086. return api_createMusicPlayer({
  1087. musicSrc: state.accompany || state.music, // 曲谱音频url
  1088. tuneSrc: "https://oss.dayaedu.com/cloud-coach/1686725501654check_music1_(1).mp3", //效音音频url
  1089. });
  1090. };
  1091. /** 获取内容平台的接口详情并初始化state信息 */
  1092. export const getMusicDetail = async (id: string) => {
  1093. const res = await getMusicSheetDetail(id);
  1094. if (res?.code === 200) {
  1095. getMusicInfo(res)
  1096. }
  1097. };
  1098. const getMusicInfo = (res: any) => {
  1099. const index = query["part-index"] ? parseInt(query["part-index"] as string) : 0;
  1100. // 原音声轨
  1101. const musicData = res.data.musicSheetSoundList?.[index] || {};
  1102. // 伴奏声轨
  1103. const accompanyData = res.data.musicSheetAccompanimentList?.[0] || {}
  1104. const musicInfo = {
  1105. ...res.data,
  1106. music: musicData.audioFileUrl || '',
  1107. accompany: accompanyData.audioFileUrl || '',
  1108. musicSheetId: musicData.musicSheetId || res.data.bizId,
  1109. track: musicData.track || '',
  1110. };
  1111. console.log("🚀 ~ musicInfo:", musicInfo);
  1112. setState(musicInfo, index);
  1113. };
  1114. const setState = (data: any, index: number) => {
  1115. state.appName = "COLEXIU";
  1116. state.detailId = data.bizId;
  1117. state.xmlUrl = data.xmlFileUrl;
  1118. state.paymentType = data.paymentType
  1119. state.partIndex = index;
  1120. state.trackId = data.track;
  1121. state.subjectId = data.subjectIds ? data.subjectIds.split(',')?.[0] : 0;
  1122. // 声部code
  1123. const subjectCode = data.subjectCodes ? data.subjectCodes.split(',')?.[0] : '';
  1124. // 乐器code
  1125. let musicalCode = data.musicalInstrumentIdCodes ? data.musicalInstrumentIdCodes.split(',')?.[0] : '';
  1126. const pitchSubject = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === subjectCode.toLocaleLowerCase())
  1127. const pitchMusical = musicalInstrumentCodeInfo.find((n) => n.code.toLocaleLowerCase() === musicalCode.toLocaleLowerCase())
  1128. state.subjectCodeId = pitchSubject ? pitchSubject.id : 0
  1129. state.musicalCodeId = pitchMusical ? pitchMusical.id : 0
  1130. state.categoriesId = data.musicCategoryId;
  1131. state.categoriesName = data.musicTagNames;
  1132. // state.enableEvaluation = data.isEvaluated ? true : false;
  1133. state.examSongId = data.bizId + "";
  1134. state.cbsExamSongId = data.id + "";
  1135. state.examSongName = data.name;
  1136. state.coverImg = data.musicCover ?? "";
  1137. // 单声部多声轨合并展示
  1138. state.isCombineRender = data.musicSheetType === "SINGLE" && data.musicSheetSoundList?.length > 1
  1139. setCustom(state.isCombineRender ? data.musicSheetSoundList?.length : 0);
  1140. // 解析扩展字段
  1141. if (data.extConfigJson) {
  1142. try {
  1143. state.extConfigJson = JSON.parse(data.extConfigJson as string);
  1144. } catch (error) {
  1145. console.error("解析扩展字段错误:", error);
  1146. }
  1147. }
  1148. state.gradualTimes = state.extConfigJson.gradualTimes;
  1149. state.repeatedBeats = state.extConfigJson.repeatedBeats || 0;
  1150. state.isEvxml = state.extConfigJson.isEvxml == 1 ? true : false;
  1151. // 曲子包含节拍器,就不开启节拍器
  1152. state.needTick = data.isUseSystemBeat && data.isPlayBeat ? true : false;
  1153. // state.isOpenMetronome = data.isUseSystemBeat ? false : true;
  1154. state.isOpenMetronome = data.isPlayBeat && !data.isUseSystemBeat ? true : false
  1155. state.isShowFingering = data.isShowFingering ? true : false;
  1156. // 设置曲谱的播放模式, APP播放(midi音频是app播放) | h5播放
  1157. state.isAppPlay = data.playMode === 'MIDI';
  1158. state.music = data.music;
  1159. state.accompany = data.accompany;
  1160. state.midiUrl = data.midiFileUrl;
  1161. state.parentCategoriesId = data.musicTag;
  1162. state.musicSheetCategoriesId = data.musicCategoryId;
  1163. state.bizMusicCategoryId = data.bizMusicCategoryId
  1164. state.playMode = data.playMode === "MP3" ? "MP3" : "MIDI";
  1165. state.originSpeed = state.speed = parseFloat(data.playSpeed) || 0;
  1166. // state.originSpeed = state.speed = data.playSpeed;
  1167. // state.playIngSpeed = data.playSpeed;
  1168. const track = data.code || data.track;
  1169. state.track = track ? track.replace(/ /g, "").toLocaleLowerCase() : "";
  1170. // 能否评测,根据当前声轨有无伴奏判断
  1171. if (state.isAppPlay) {
  1172. state.enableEvaluation = state.midiUrl ? true : false
  1173. } else {
  1174. state.enableEvaluation = state.accompany ? true : false
  1175. }
  1176. state.isConcert = data.musicSheetType === "CONCERT" ? true : false;
  1177. // multiTracksSelection 返回为空,默认代表全部分轨
  1178. state.canSelectTracks = data.multiTracksSelection === "null" || data.multiTracksSelection === "" || data.multiTracksSelection === null ? [] : data.multiTracksSelection?.split(',');
  1179. // 开启预备小节
  1180. state.isOpenPrepare = true;
  1181. state.extStyleConfigJson = data.extStyleConfigJson || {}
  1182. // console.log("🚀 ~ state.subjectId:", state.subjectId, state.track as any , state.subjectId)
  1183. // 是否打击乐
  1184. /**
  1185. * 是否打击乐:AMPLITUDE & 节奏练习:DECIBELS
  1186. * evaluationStandard:("评测标准 节奏 AMPLITUDE 音准 FREQUENCY 分贝 DECIBELS")
  1187. * 打击乐&节奏练习,没有跟练模式
  1188. */
  1189. // state.isPercussion = isRhythmicExercises();
  1190. state.isPercussion = data.evaluationStandard === "AMPLITUDE" || data.evaluationStandard === "DECIBELS";
  1191. state.evaluationStandard = data.evaluationStandard?.toLocaleLowerCase() || ''
  1192. // 设置是否特殊曲谱, 是特殊曲谱取反(不理解之前的思考逻辑), 使用后台设置的速度
  1193. state.isSpecialBookCategory = !classids.includes(Number(data.musicCategoryId));
  1194. // 设置指法
  1195. // const code = state.isConcert ? mappingVoicePart(state.trackId, "ENSEMBLE") : mappingVoicePart(state.subjectId, "INSTRUMENT");
  1196. /**
  1197. * 各平台的乐器声部id不统一,为了兼容处理老的数据,加上乐器code码,此码唯一
  1198. * 获取指法code
  1199. */
  1200. const code = state.isConcert ? matchVoicePart(state.trackId, "CONCERT") : matchVoicePart(state.musicalCodeId, "SINGLE");
  1201. state.fingeringInfo = subjectFingering(code);
  1202. console.log("🚀 ~ state.fingeringInfo:", code, state.fingeringInfo, state.trackId, state.track);
  1203. state.musicalCodeId = state.fingeringInfo?.id || 0
  1204. state.musicalCode = musicalInstrumentCodeInfo.find(item => item.id === state.musicalCodeId)?.code || state.trackId
  1205. ; (window as any).DYSubjectId = state.musicalCodeId
  1206. // 开启自定义每行显示的小节数
  1207. ; (window as any).customSectionAmount = true
  1208. // 标识是课堂乐器,用于移调时进行区分处理
  1209. ; (window as any).DYProjectName = 'musicScore';
  1210. // 如果切换的声轨没有指法,择指法开关置灰并且不可点击
  1211. if (!state.fingeringInfo.name && state.setting.displayFingering) {
  1212. state.setting.displayFingering = false
  1213. }
  1214. // 检测是否原音和伴奏都有
  1215. if (!state.music || !state.accompany) {
  1216. state.playSource = state.music ? "music" : "background";
  1217. }
  1218. // 如果是PC端,放大曲谱
  1219. state.platform = query.platform?.toLocaleUpperCase() || "";
  1220. if (state.platform === IPlatform.PC) {
  1221. state.zoom = query.zoom || 1.5;
  1222. state.enableEvaluation = false;
  1223. }
  1224. /**
  1225. * 默认渲染什么谱面类型 & 能否转谱逻辑
  1226. * 渲染类型:首先取url参数musicRenderType,没有该参数则取musicalInstruments字段匹配的当前分轨的defaultScore,没有匹配到则取默认值('firstTone')
  1227. * 能否转谱:先取isConvertibleScore字段,如果isConvertibleScore为true,则取musicalInstruments字段匹配的当前分轨的transferFlag,都为true则可以转谱
  1228. *
  1229. */
  1230. let pitchTrack = null
  1231. if (state.isConcert) {
  1232. musicalCode = musicalInstrumentCodeInfo.find((item: any) => item.id === state.musicalCodeId)?.code
  1233. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1234. } else {
  1235. pitchTrack = data.musicalInstruments?.find((item: any) => item.code === musicalCode)
  1236. }
  1237. let musicalRenderType = ''
  1238. if (pitchTrack?.defaultScore) {
  1239. musicalRenderType = pitchTrack?.defaultScore === 'STAVE' ? 'staff' : pitchTrack?.defaultScore === 'JIAN' ? 'fixedTone' : pitchTrack?.defaultScore === 'FIRST' ? 'firstTone' : ''
  1240. }
  1241. state.musicRenderType = query.musicRenderType || musicalRenderType || EnumMusicRenderType.firstTone;
  1242. /**
  1243. * TODO:摇篮曲特殊处理
  1244. */
  1245. if (['1788501975122489346', '1788502467554750466', '1789839575249596417'].includes(state.cbsExamSongId)) {
  1246. if (state.musicRenderType === 'fixedTone') {
  1247. state.musicRenderType = EnumMusicRenderType.firstTone;
  1248. }
  1249. }
  1250. state.enableNotation = pitchTrack ? data.isConvertibleScore && pitchTrack.transferFlag : data.isConvertibleScore
  1251. console.log("state对象", state);
  1252. // 评测基准频率
  1253. state.baseFrequency = data.evaluationFrequency ? data.evaluationFrequency.split(",")[0] : 440
  1254. state.baseFrequency = Number(state.baseFrequency)
  1255. // 用户上次的频率和基准频率误差超过10,则重置
  1256. if (Math.abs(state.setting.frequency - state.baseFrequency) > 10) {
  1257. state.setting.frequency = state.baseFrequency >= 0 ? state.baseFrequency : 440
  1258. } else {
  1259. state.setting.frequency = state.setting.frequency || state.baseFrequency
  1260. }
  1261. };
  1262. // 多分轨合并显示标示
  1263. const setCustom = (trackNum?: number) => {
  1264. if (trackNum || state.extConfigJson.multitrack) {
  1265. state.multitrack = trackNum || 0
  1266. setGlobalData("multitrack", trackNum || state.extConfigJson.multitrack);
  1267. }
  1268. };
  1269. /** 跟练模式播放节拍器(叮咚) */
  1270. export const followBeatPaly = () => {
  1271. let metroTimer: any = null;
  1272. if (!followData.start) {
  1273. clearTimeout(metroTimer)
  1274. metroTimer = null
  1275. return;
  1276. }
  1277. const time = state.measureTime * 1000 / metronomeData.totalNumerator
  1278. requestAnimationFrame(() => {
  1279. const endTime = Date.now();
  1280. if (endTime - state.beatStartTime < time) {
  1281. followBeatPaly();
  1282. } else {
  1283. // metroTimer = setTimeout(() => {
  1284. // metronomeData.metro?.simulatePlayAudio()
  1285. // startTime = Date.now();
  1286. // followBeatPaly();
  1287. // }, time);
  1288. metronomeData.metro?.simulatePlayAudio()
  1289. state.beatStartTime = Date.now();
  1290. followBeatPaly();
  1291. }
  1292. });
  1293. };
  1294. // 音符添加bbox
  1295. export const addNoteBBox = (list: any[]) => {
  1296. let voicesBBox: any = null;
  1297. for (let i = 0; i < list.length; i++) {
  1298. const note = list[i];
  1299. const { svgElement, multipleRestMeasures, totalMultipleRestMeasures, stave } = note;
  1300. /**
  1301. * 兼容合并休止小节没有音符的情况,将合并的小节宽度等分,音符位置就在等分的位置
  1302. */
  1303. let bbox: any = null;
  1304. if (svgElement?.attrs.id) {
  1305. // @ts-ignore
  1306. bbox = document.getElementById(`vf-${svgElement?.attrs?.id}`)?.getBBox();
  1307. bbox = {
  1308. x: bbox?.x * state.zoom,
  1309. y: bbox?.y * state.zoom,
  1310. width: bbox?.width * state.zoom,
  1311. height: bbox?.height * state.zoom,
  1312. }
  1313. } else {
  1314. // @ts-ignore
  1315. let currentVoicesBBox: any = document.getElementById(`${stave?.attrs?.id}`)?.nextSibling?.getBBox();
  1316. const svgBodyBBox: any = document.getElementById('musicAndSelection')?.getBoundingClientRect();
  1317. if (!currentVoicesBBox && multipleRestMeasures <= totalMultipleRestMeasures) {
  1318. currentVoicesBBox = voicesBBox;
  1319. }
  1320. let nextIndex = i + 1;
  1321. while (!list[nextIndex]?.id && nextIndex < list.length) {
  1322. nextIndex += 1;
  1323. }
  1324. // 休止小节的开头和下一个音符之间的间距
  1325. let multipleWidth: any = currentVoicesBBox?.width * state.zoom;
  1326. if (list[nextIndex]?.id) {
  1327. // @ts-ignore
  1328. multipleWidth = document.getElementById(`${list[nextIndex]?.stave?.attrs?.id}`)?.getBBox()?.x * state.zoom - currentVoicesBBox?.x * state.zoom;
  1329. }
  1330. const ratioWidth = multipleWidth / totalMultipleRestMeasures || 0;
  1331. bbox = currentVoicesBBox ? {
  1332. bottom: currentVoicesBBox.bottom,
  1333. height: 30,
  1334. left: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1335. right: currentVoicesBBox.y,
  1336. top: currentVoicesBBox.top,
  1337. width: 1,
  1338. x: currentVoicesBBox.x * state.zoom + ratioWidth * (multipleRestMeasures - 1),
  1339. y: currentVoicesBBox.y,
  1340. svgBodyLeft: svgBodyBBox?.x,
  1341. } : null;
  1342. voicesBBox = currentVoicesBBox;
  1343. }
  1344. note.bbox = bbox;
  1345. }
  1346. }
  1347. // 一行谱模式,创建固定的光标
  1348. export const createFixedCursor = () => {
  1349. if (!state.isSingleLine) return;
  1350. const svg: any = document.getElementById("osmdSvgPage1");
  1351. state.osmdSvgDom = svg;
  1352. const scrollDom = document.getElementById("musicAndSelection");
  1353. const cursorDom = document.getElementById("cursorImg-0");
  1354. state.fistNoteLeft = cursorDom?.getBoundingClientRect()?.left || 0;
  1355. state.osdmScrollDom = scrollDom;
  1356. state.cursorDom = cursorDom;
  1357. let copyCursor: any = cursorDom?.cloneNode(true);
  1358. if (copyCursor) {
  1359. copyCursor.setAttribute('id', 'cursor-copy');
  1360. copyCursor.style.position = 'sticky';
  1361. copyCursor.style.zIndex = '2';
  1362. // if (!state.times[0]?.id) {
  1363. // copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 3 + 'px';
  1364. // }
  1365. copyCursor.style.left = state.times[0]?.bbox?.x + state.times[0]?.bbox?.width / 2 - 1 + 'px';
  1366. copyCursor.style.height = parseFloat(copyCursor.style.height) * 3 + 'px';
  1367. copyCursor.style.opacity = state.moveType === 'uniform' ? 0 : 1;
  1368. // copyCursor.style.background = 'red';
  1369. copyCursor && scrollDom?.appendChild(copyCursor);
  1370. // 创建左侧背景dom
  1371. // @ts-ignore
  1372. const firstMeasureBBox: any = document.querySelector('.vf-measure')?.getBBox();
  1373. const leftDom = document.createElement("div");
  1374. leftDom.style.width = state.times[0]?.bbox?.x - firstMeasureBBox?.x * state.zoom + 'px';
  1375. leftDom.style.height = firstMeasureBBox?.height * state.zoom + 'px';
  1376. leftDom.style.left = firstMeasureBBox?.x * state.zoom + 'px';
  1377. leftDom.style.transform = 'translateY(20px)';
  1378. leftDom.classList.add('leftNoteBg');
  1379. // scrollDom?.appendChild(leftDom);
  1380. }
  1381. }
  1382. /** 计算首尾音符的间距 */
  1383. export const calculateDistance = () => {
  1384. const firstNoteBBox = state.times[0]?.bbox;
  1385. const lastNoteBBox = state.times.last()?.bbox;
  1386. if (firstNoteBBox && lastNoteBBox) {
  1387. const noteDistance = lastNoteBBox.x - firstNoteBBox.x + lastNoteBBox.width / 2 - firstNoteBBox.width / 2 - 1;
  1388. console.log('首尾间距', noteDistance)
  1389. state.noteDistance = noteDistance || 0;
  1390. }
  1391. }
  1392. /** 跳动svgdom */
  1393. export const moveSvgDom = (skipNote?: boolean) => {
  1394. // const cursorLeft = state.cursorDom?.getBoundingClientRect()?.left || 0;
  1395. // const leftValue = parseFloat(state.cursorDom.style.left) - 47 - 20;
  1396. // console.log(cursorLeft,leftValue,'光标位置')
  1397. // state.osmdSvgDom.style.transform = `translateX(${-leftValue}px)`;
  1398. // state.osdmScrollDom.scrollLeft = leftValue
  1399. // console.log('当前音符',state.activeNoteIndex)
  1400. state.times.forEach((item: any, idx: number) => {
  1401. const svgEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}`)
  1402. const stemEl = document.getElementById(`vf-${state.times[idx]?.svgElement?.attrs?.id}-stem`)
  1403. if ((item.i === state.activeNoteIndex || item.id === state.times[state.activeNoteIndex].id) && item.svgElement) {
  1404. svgEl?.classList.add('noteActive')
  1405. stemEl?.classList.add('noteActive')
  1406. } else {
  1407. svgEl?.classList.remove('noteActive')
  1408. stemEl?.classList.remove('noteActive')
  1409. }
  1410. })
  1411. // document.getElementById('cursor-copy')?.classList.add('cursorAnimate');
  1412. /**
  1413. * 计算需要移动的距离
  1414. * 当前选中的音符和第一个音符之间的间距
  1415. */
  1416. if (skipNote) {
  1417. const distance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 2 - state.times[0].bbox?.width / 2;
  1418. state.osdmScrollDom.scrollTo({
  1419. left: distance,
  1420. behavior: "smooth",
  1421. });
  1422. }
  1423. }
  1424. /** 平滑移动svgdom */
  1425. export const smoothMoveSvgDom = () => {
  1426. const currentTime = getAudioCurrentTime();
  1427. const matchNoteIdx = state.times.findIndex((item: any) => Math.abs(item.time - currentTime) * 1000 < 100)
  1428. // if (matchNoteIdx >= 0) {
  1429. // console.log('匹配',matchNoteIdx,currentTime)
  1430. // }
  1431. if (currentTime <= state.fixtime) return;
  1432. if (currentTime > state.times.last()?.time) return;
  1433. // console.log('跳转音符',currentTime)
  1434. const currentBBox = state.times[state.activeNoteIndex]?.bbox;
  1435. let nextIndex = state.activeNoteIndex + 1;
  1436. let nextBBox = state.times[nextIndex]?.bbox;
  1437. while (!nextBBox && nextIndex < state.times.length) {
  1438. nextIndex += 1;
  1439. nextBBox = state.times[nextIndex]?.bbox;
  1440. }
  1441. // 下一个音符和当前播放音符之间的间距
  1442. let noteDistance = nextBBox?.x - state.times[state.activeNoteIndex].bbox?.x + nextBBox?.width / 4 - state.times[state.activeNoteIndex].bbox?.width / 4 || 0
  1443. if (noteDistance) {
  1444. // 当前的音符和下一个音符之间的时值
  1445. const noteDuration = state.times[nextIndex].time - state.times[state.activeNoteIndex]?.time;
  1446. // 当前时值在该区间的占比
  1447. const playProgress = (currentTime - state.times[state.activeNoteIndex]?.time) / noteDuration;
  1448. // 如果当前播放的音符是休止小节的,实际没有音符
  1449. // if (!state.times[state.activeNoteIndex]?.id && state.times[state.activeNoteIndex]?.multipleRestMeasures && state.times[state.activeNoteIndex+1].id) {
  1450. // noteDistance = noteDistance - state.times[state.activeNoteIndex]?.bbox?.svgBodyLeft;
  1451. // }
  1452. const distance = noteDistance * playProgress;
  1453. // 上一个音符和第一个音符的间距
  1454. let preDistance = state.times[state.activeNoteIndex].bbox?.x - state.times[0].bbox?.x + state.times[state.activeNoteIndex].bbox?.width / 4;
  1455. // console.log(state.activeNoteIndex,'滑动', distance, preDistance, state.osdmScrollDom.scrollLeft, noteDistance, nextIndex, currentTime, noteDuration )
  1456. // console.log('当前音符',state.activeNoteIndex,'距离',noteDistance,'比例',playProgress,'上一个距离',preDistance,'时值',currentTime, noteDuration)
  1457. //console.log('滑动','音符:',state.activeNoteIndex,'小节:', state.activeMeasureIndex)
  1458. state.osdmScrollDom.scrollLeft = distance + preDistance;
  1459. } else {
  1460. const playProgress = (currentTime - state.times[0]?.time) / state.times.last()?.time
  1461. const distance = state.noteDistance * playProgress;
  1462. state.osdmScrollDom.scrollLeft = distance;
  1463. }
  1464. }
  1465. // 匀速平移
  1466. export const uniformMoveSvgDom = () => {
  1467. const currentTime = getAudioCurrentTime();
  1468. if (currentTime <= state.fixtime) return;
  1469. if (currentTime > state.times.last()?.time) return;
  1470. const playProgress = (currentTime - state.fixtime) / state.times.last()?.time;
  1471. const distance = playProgress * state.noteDistance || 0;
  1472. state.osdmScrollDom.scrollLeft = distance;
  1473. }